package com.plian.system.service.dwh.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.dwh.DwhStaffManagementBean;
import com.plian.system.bean.staff.*;
import com.plian.system.cache.StaffCache;
import com.plian.system.common.status.CustomCode;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dto.dwh.DwhStaffManagementDTO;
import com.plian.system.entity.dwh.DwhStaffManagement;
import com.plian.system.entity.hr.dept.Dept;
import com.plian.system.entity.hr.staff.*;
import com.plian.system.entity.pm.property.PropertyBasics;
import com.plian.system.entity.sys.Dict;
import com.plian.system.entity.sys.FormHistoryRecord;
import com.plian.system.enumeratea.PartTimeStatus;
import com.plian.system.excel.ImportExcelUtil;
import com.plian.system.excel.ImportResult;
import com.plian.system.mapper.dwh.DwhStaffManagementMapper;
import com.plian.system.mapper.hr.staff.DirectorMapper;
import com.plian.system.mapper.hr.staff.SupervisorMapper;
import com.plian.system.mapper.pm.property.PropertyBasicsMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.base.ListEqualsUtil;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.pdf.OutPdf;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.dwh.IDwhStaffManagementService;
import com.plian.system.service.dwh.check.DwhStaffManagementCheckData;
import com.plian.system.service.dwh.check.DwhStaffManagementCheckDataSon;
import com.plian.system.service.hr.dept.IDeptService;
import com.plian.system.service.hr.recruitment.IPartTimeInfoService;
import com.plian.system.service.hr.staff.*;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.dict.IDictService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.sys.system.IFormHistoryRecordService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.service.wfTwo.WorkflowTwoService;
import com.plian.system.service.yth.IStafffilesService;
import com.plian.system.vo.dwh.DwhStaffManagementChartsVO;
import com.plian.system.vo.dwh.DwhStaffManagementVO;
import com.plian.system.vo.hr.staff.*;
import com.plian.system.vo.pm.property.MainStaffInfoVO;
import com.plian.system.vo.pm.property.ProStaffInfoVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.dwh.DwhStaffManagementWrapper;
import com.plian.system.wrapper.hr.staff.*;
import lombok.AllArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.BaseConstant.BASE64_KEY;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 员工档案 服务实现类
 *
 * @author gangan
 * @since 2019-09-29
 */
@Service
@AllArgsConstructor
public class DwhStaffManagementImpl extends BaseServiceImpl<DwhStaffManagementMapper, DwhStaffManagement> implements IDwhStaffManagementService, BaseFlowService {


    private IAppointRemoveService appointRemoveService;
    private IEducationDegreeService educationDegreeService;
    private IWorkExperienceService workExperienceService;
    private IRewardsPunishmentsService rewardsPunishmentsService;
    private IAnnualAssessmentService annualAssessmentService;
    private ISocialRelationsService socialRelationsService;
    private IPractitionerCertificateService practitionerCertificateService;
    private ITechnicalQualificationService technicalQualificationService;
    private ITrainService trainService;
    private IOverseasMembersService overseasMembersService;
    private FormWorkflowService formWorkflowService;
    private WorkflowTwoService workflowTwoService;
    private BaseInfoService baseInfoService;
    private OrgzationDao orgzationDao;
    private IPartTimeInfoService partTimeInfoService;
    private IDeptService deptService;
    private OrgzationService orgzationService;
    private Environment environment;
    private IFormHistoryRecordService formHistoryRecordService;
    private AppointRemoveWrapper appointRemoveWrapper;
    private EducationDegreeWrapper educationDegreeWrapper;
    private RewardsPunishmentsWrapper rewardsPunishmentsWrapper;
    private AnnualAssessmentWrapper annualAssessmentWrapper;
    private SocialRelationsWrapper socialRelationsWrapper;
    private DwhStaffManagementWrapper dwhStaffManagementWrapper;
    private PractitionerCertificateWrapper practitionerCertificateWrapper;
    private TechnicalQualificationWrapper technicalQualificationWrapper;
    private TrainWrapper trainWrapper;
    private OverseasMembersWrapper overseasMembersWrapper;
    private WorkExperienceWrapper workExperienceWrapper;

    private IStafffilesService stafffilesService;

    private final IOrgService orgService;

    private ISysUserService userService;

    private PropertyBasicsMapper propertyBasicsMapper;

    private DirectorMapper directorMapper;

    private SupervisorMapper supervisorMapper;

    private IDictService dictService;

    private IFormCodeService formCodeService;

    private static final String appointRemoveErrMsg = "任免记录";
    private static final String educationDegreeErrMsg = "学历学位";
    private static final String workExperienceErrMsg = "工作经历";
    private static final String rewardsPunishmentsErrMsg = "奖惩情况";
    private static final String annualAssessmentErrMsg = "年度考核结果";
    private static final String socialRelationsErrMsg = "家庭及社会关系";
    private static final String practitionerCertificateErrMsg = "从业资格证书";
    private static final String technicalQualificationErrMsg = "专业技术资格";
    private static final String trainErrMsg = "近五年三个月以上培训情况";
    private static final String overseasMembersErrMsg = "侨眷情况";


    //名称转cod 用参照字典（参照key,<name,id>）(需确保每个名字唯一)
    private static HashMap<String, Map<String, String>> nameMap = new HashMap<>();
    //部门参照(所属企业id,<部门名称,部门id>)
    private static HashMap<String, Map<String, Long>> deptUnitMap = new HashMap<>();
    //部门参照(所属企业id,<部门名称,部门Code>)
    private static HashMap<String, Map<String, String>> deptUnitCodeMap = new HashMap<>();

    // 字典map
    private static HashMap<String, List<String>> codeMap = new HashMap<>();

    // report接口 entity类转vo使用
    private static Map<String, String> allCodeMap = new HashMap<>();
    private static Map<Long, String> deptMap = new HashMap<>();
    private static Map<String, String> orgMap = new HashMap<>();
    private static Map<String, String> fileNameMap = new HashMap<>();


    private static final String managementCategoryCode = "027";

    /**
     * 导入
     *
     * @return object
     */
    @Override
    @Async("ttlExecutor")
    public Future<ImportResult> importExcel(String progressId, InputStream inputStream, Boolean isCover) {
        String progress = "progress";
        String key = progressId + "#half:hour";
        try {
            List<String> codeList = new ArrayList<>();
            byte[] bytes = IOUtils.toByteArray(inputStream);

            inputStream = new ByteArrayInputStream(bytes);

            List<Object> staffReadExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(1).headRowNumber(1).head(DwhStaffManagementBean.class)
                            .registerReadListener(new PageReadListener<>(list -> staffReadExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(staffReadExcels);
            int size = staffReadExcels.size();
            //在所有校验前统一初始化所有字典
            initMap();
            //获取当前单位现有所有人事数据列表
            List<DwhStaffManagement> staffFilesList = list(new QueryWrapper<DwhStaffManagement>().eq("company_name_id", TokenUtil.getTokenOrgId()));
            //系统现有编码检查
            ImportResult importResult = DwhStaffManagementCheckData.checkStaffData(staffReadExcels, staffFilesList, key, codeMap, nameMap, deptUnitMap, deptUnitCodeMap, isCover);
            if (!importResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, importResult.getMsg());
                return new AsyncResult<>(importResult);
            }
            for (Object object : staffReadExcels) {
                DwhStaffManagementBean staffFilesExcelBean = (DwhStaffManagementBean) object;
                String code = staffFilesExcelBean.getStaffCode();
                codeList.add(code);
            }
            //任免记录
            inputStream.reset();
            List<Object> appoiontExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(3).headRowNumber(1).head(AppointRemoveExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> appoiontExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(appoiontExcels);
            ImportResult appointResult = DwhStaffManagementCheckDataSon.checkAppointRemove(appoiontExcels, codeList, staffFilesList, isCover);
            if (!appointResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, appointResult.getMsg());
                return new AsyncResult<>(appointResult);
            }
            //学历学位子表
            inputStream.reset();
            List<Object> educationDegreeExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(4).headRowNumber(1).head(EducationDegreeExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> educationDegreeExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(educationDegreeExcels);
            ImportResult educationDegreeResult = DwhStaffManagementCheckDataSon.checkEducationDegree(educationDegreeExcels, codeList, staffFilesList, codeMap, isCover);
            if (!educationDegreeResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, educationDegreeResult.getMsg());
                return new AsyncResult<>(educationDegreeResult);
            }
            //工作经历
//			inputStream.reset();
//			List<Object> workExperienceExcels = EasyExcelFactory.read(
//				inputStream,new Sheet(6,1, WorkExperienceExcelBean.class)
//			);
//			ImportExcelUtil.filterEmpty(workExperienceExcels);
//			ImportResult workExperienceResult = StaffExcelCheckDataSon.checkWorkExperience(workExperienceExcels,codeList,staffFilesList,codeMap,isCover);
//			if(!workExperienceResult.isSuccess()){
//				CacheUtil.put(progress, progress, key, workExperienceResult.getMsg());
//				return new AsyncResult<>(workExperienceResult);
//			}
            //奖惩情况
            inputStream.reset();
            List<Object> rewardsPunishmentExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(5).headRowNumber(1).head(RewardsPunishmentsExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> rewardsPunishmentExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(rewardsPunishmentExcels);
            ImportResult rewardsPunishmentsResult = DwhStaffManagementCheckDataSon.checkRewardsPunishments(rewardsPunishmentExcels, codeList, staffFilesList, isCover);
            if (!rewardsPunishmentsResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, rewardsPunishmentsResult.getMsg());
                return new AsyncResult<>(rewardsPunishmentsResult);
            }
            //年度考核结果
            inputStream.reset();
            List<Object> annualAssessmentExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(6).headRowNumber(1).head(AnnualAssessmentExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> annualAssessmentExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(annualAssessmentExcels);
            ImportResult annualAssessResult = DwhStaffManagementCheckDataSon.checkAnnualAssessment(annualAssessmentExcels, codeList, staffFilesList, isCover);
            if (!annualAssessResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, annualAssessResult.getMsg());

                return new AsyncResult<>(annualAssessResult);
            }
            //家庭及社会关系
            inputStream.reset();
            List<Object> socialRelationExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(7).headRowNumber(1).head(SocialRelationsExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> socialRelationExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(socialRelationExcels);
            ImportResult socialRelationResult = DwhStaffManagementCheckDataSon.checkSocialRelations(socialRelationExcels, codeList, staffFilesList, codeMap, isCover);
            if (!socialRelationResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, socialRelationResult.getMsg());
                return new AsyncResult<>(socialRelationResult);
            }
            //从业资格证书
            inputStream.reset();
            List<Object> practitionerCertificateExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(8).headRowNumber(1).head(PractitionerCertificateExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> practitionerCertificateExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(practitionerCertificateExcels);
            ImportResult practitionerCertificateResult = DwhStaffManagementCheckDataSon.checkPractitionerCertificate(practitionerCertificateExcels, codeList, staffFilesList, isCover);
            if (!practitionerCertificateResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, practitionerCertificateResult.getMsg());

                return new AsyncResult<>(practitionerCertificateResult);
            }
            //专业技术资格
            inputStream.reset();
            List<Object> technicalExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(9).headRowNumber(1).head(TechnicalQualificationExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> technicalExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(technicalExcels);
            ImportResult technicalResult = DwhStaffManagementCheckDataSon.checkTechnicalQualification(technicalExcels, codeList, staffFilesList, codeMap, isCover);
            if (!technicalResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, technicalResult.getMsg());

                return new AsyncResult<>(technicalResult);
            }
            //近五年三个月以上培训情况
            inputStream.reset();
            List<Object> trainExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(10).headRowNumber(1).head(TrainExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> trainExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(trainExcels);
            ImportResult trainResult = DwhStaffManagementCheckDataSon.checkTrain(trainExcels, codeList, staffFilesList, isCover);
            if (!trainResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, trainResult.getMsg());

                return new AsyncResult<>(trainResult);
            }
            //侨眷情况
            inputStream.reset();
            List<Object> overseaExcels = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(11).headRowNumber(1).head(OverseasMembersExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> overseaExcels.addAll(list))).build());
            ImportExcelUtil.filterEmpty(overseaExcels);
            ImportResult overseaResult = DwhStaffManagementCheckDataSon.checkOverseasMembers(overseaExcels, codeList, staffFilesList, codeMap, isCover);
            if (!overseaResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, overseaResult.getMsg());

                return new AsyncResult<>(overseaResult);
            }

            int count = 0;
            //主表存储
            for (Object object : staffReadExcels) {
                DwhStaffManagement staffFiles = (DwhStaffManagement) ImportExcelUtil.getEntityByExcelBean((DwhStaffManagementBean) object, new DwhStaffManagement());
                //入库
                try {
//					staffFiles.setIsOutdirector(1);
//					staffFiles.setIsOutsupervisor(1);

                    DwhStaffManagement oldStaffFiles = searchStaffByStaffCode(staffFiles.getStaffCode());
                    if (oldStaffFiles != null) {
                        staffFiles.setId(oldStaffFiles.getId());
                        staffFiles.setDef18(Long.valueOf("1"));
                        staffFiles.setIsOut(1);
                        // version更新
                        staffFiles.setVersion(String.valueOf(Integer.parseInt(oldStaffFiles.getVersion()) + 1));

                    } else {
                        staffFiles.setDef18(Long.valueOf("1"));
                        staffFiles.setIsOut(1);
                        staffFiles.setStatus(FormStatusConstant.UNREVIEWED);
                        staffFiles.setVersion("1");
                    }
                    staffFiles.setStaffCode(EncryptUtil.encryptBase64(staffFiles.getStaffCode(), BASE64_KEY));
                    staffFiles.setDocumentNumber(staffFiles.getStaffCode());
                    saveOrUpdate(staffFiles);
                    count++;
                    int value = count * 100 / size;
                    CacheUtil.put(progress, progress, key, value + 100);
                } catch (Exception e) {
                    log.error(ExceptionUtils.getStackTrace(e));
                    log.error(staffFiles + "导入失败");
                    CacheUtil.put(progress, progress, key, staffFiles + "导入失败");

                    return new AsyncResult<>(new ImportResult(false, staffFiles + "导入失败"));
                }
            }
            //任免记录子表
            HashMap<String, List<AppointRemove>> appointRemoveMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : appoiontExcels) {
                AppointRemove appointRemove = (AppointRemove) ImportExcelUtil.getEntityByExcelBean((AppointRemoveExcelBean) readExcels, new AppointRemove());
                if (appointRemoveMap.containsKey(appointRemove.getDef1())) {
                    appointRemoveMap.get(appointRemove.getDef1()).add(appointRemove);
                } else {
                    List<AppointRemove> value = new ArrayList<>();
                    value.add(appointRemove);
                    appointRemoveMap.put(appointRemove.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<AppointRemove>> entry : appointRemoveMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<AppointRemove> oldAppointRemove = appointRemoveService.ListByPid(staffFiles.getId());
                        if (oldAppointRemove.size() > 0) {
                            List<Long> ids = oldAppointRemove.parallelStream().map(AppointRemove::getId).collect(Collectors.toList());
                            appointRemoveService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        appointRemoveService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(appointRemoveErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, appointRemoveErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, appointRemoveErrMsg + "导入失败"));
            }

            //学历学位
            HashMap<String, List<EducationDegree>> educationDegreeMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : educationDegreeExcels) {
                EducationDegree educationDegree = (EducationDegree) ImportExcelUtil.getEntityByExcelBean((EducationDegreeExcelBean) readExcels, new EducationDegree());
                if (educationDegreeMap.containsKey(educationDegree.getDef1())) {
                    educationDegreeMap.get(educationDegree.getDef1()).add(educationDegree);
                } else {
                    List<EducationDegree> value = new ArrayList<>();
                    value.add(educationDegree);
                    educationDegreeMap.put(educationDegree.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<EducationDegree>> entry : educationDegreeMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<EducationDegree> oldEducationDegree = educationDegreeService.ListByPid(staffFiles.getId());
                        if (oldEducationDegree.size() > 0) {
                            List<Long> ids = oldEducationDegree.parallelStream().map(EducationDegree::getId).collect(Collectors.toList());
                            educationDegreeService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        educationDegreeService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(educationDegreeErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, educationDegreeErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, educationDegreeErrMsg + "导入失败"));
            }
            //工作经历
//			HashMap<String,List<WorkExperience>> workExperienceMap = new HashMap<>();
//			//对每条子表数据进行分组
//			for(Object readExcels:workExperienceExcels) {
//				WorkExperience workExperience = (WorkExperience) ImportExcelUtil.getEntityByExcelBean((WorkExperienceExcelBean) readExcels, new WorkExperience());
//				if (workExperienceMap.containsKey(workExperience.getDef1())) {
//					workExperienceMap.get(workExperience.getDef1()).add(workExperience);
//				} else {
//					List<WorkExperience> value = new ArrayList<>();
//					value.add(workExperience);
//					workExperienceMap.put(workExperience.getDef1(), value);
//				}
//			}
//			//入库
//			try{
//				for(HashMap.Entry<String,List<WorkExperience>> entry : workExperienceMap.entrySet()){
//					StaffFiles staffFiles = searchStaffByStaffCode(entry.getKey());
//					//覆盖时删除原对应主表记录下属的所有旧子表记录
//					if(isCover) {
//						List<WorkExperience> oldWorkExperience = workExperienceService.ListByPid(staffFiles.getId());
//						if(oldWorkExperience.size()>0) {
//							List<Long> ids = oldWorkExperience.parallelStream().map(WorkExperience::getId).collect(Collectors.toList());
//							workExperienceService.deleteLogic(ids);
//						}
//					}
//					entry.getValue().forEach(x->{
//						x.setStaffFilesId(staffFiles.getId());
//						x.setDef1("");
//						workExperienceService.saveOrUpdate(x);
//					});
//				}
//			}catch(Exception e){
//				log.error(workExperienceErrMsg + "导入失败");
//				CacheUtil.put(progress, progress, key,workExperienceErrMsg + "导入失败");
//
//				return new AsyncResult<>(new ImportResult(false,workExperienceErrMsg + "导入失败"));
//			}
            //奖惩情况
            HashMap<String, List<RewardsPunishments>> rewardsPunishmentsMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : rewardsPunishmentExcels) {
                RewardsPunishments rewardsPunishments = (RewardsPunishments) ImportExcelUtil.getEntityByExcelBean((RewardsPunishmentsExcelBean) readExcels, new RewardsPunishments());
                if (rewardsPunishmentsMap.containsKey(rewardsPunishments.getDef1())) {
                    rewardsPunishmentsMap.get(rewardsPunishments.getDef1()).add(rewardsPunishments);
                } else {
                    List<RewardsPunishments> value = new ArrayList<>();
                    value.add(rewardsPunishments);
                    rewardsPunishmentsMap.put(rewardsPunishments.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<RewardsPunishments>> entry : rewardsPunishmentsMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<RewardsPunishments> oldRewardsPunishments = rewardsPunishmentsService.ListByPid(staffFiles.getId());
                        if (oldRewardsPunishments.size() > 0) {
                            List<Long> ids = oldRewardsPunishments.parallelStream().map(RewardsPunishments::getId).collect(Collectors.toList());
                            rewardsPunishmentsService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        rewardsPunishmentsService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(rewardsPunishmentsErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, rewardsPunishmentsErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, rewardsPunishmentsErrMsg + "导入失败"));
            }
            //年度考核结果
            HashMap<String, List<AnnualAssessment>> annualAssessmentMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : annualAssessmentExcels) {
                AnnualAssessment annualAssessment = (AnnualAssessment) ImportExcelUtil.getEntityByExcelBean((AnnualAssessmentExcelBean) readExcels, new AnnualAssessment());
                if (annualAssessmentMap.containsKey(annualAssessment.getDef1())) {
                    annualAssessmentMap.get(annualAssessment.getDef1()).add(annualAssessment);
                } else {
                    List<AnnualAssessment> value = new ArrayList<>();
                    value.add(annualAssessment);
                    annualAssessmentMap.put(annualAssessment.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<AnnualAssessment>> entry : annualAssessmentMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<AnnualAssessment> oldAnnualAssessment = annualAssessmentService.ListByPid(staffFiles.getId());
                        if (oldAnnualAssessment.size() > 0) {
                            List<Long> ids = oldAnnualAssessment.parallelStream().map(AnnualAssessment::getId).collect(Collectors.toList());
                            annualAssessmentService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        annualAssessmentService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(annualAssessmentErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, annualAssessmentErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, annualAssessmentErrMsg + "导入失败"));
            }
            //家庭及社会关系
            HashMap<String, List<SocialRelations>> socialRelationsMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : socialRelationExcels) {
                SocialRelations socialRelations = (SocialRelations) ImportExcelUtil.getEntityByExcelBean((SocialRelationsExcelBean) readExcels, new SocialRelations());
                if (socialRelationsMap.containsKey(socialRelations.getDef1())) {
                    socialRelationsMap.get(socialRelations.getDef1()).add(socialRelations);
                } else {
                    List<SocialRelations> value = new ArrayList<>();
                    value.add(socialRelations);
                    socialRelationsMap.put(socialRelations.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<SocialRelations>> entry : socialRelationsMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<SocialRelations> oldSocialRelations = socialRelationsService.ListByPid(staffFiles.getId());
                        if (oldSocialRelations.size() > 0) {
                            List<Long> ids = oldSocialRelations.parallelStream().map(SocialRelations::getId).collect(Collectors.toList());
                            socialRelationsService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        socialRelationsService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(socialRelationsErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, socialRelationsErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, socialRelationsErrMsg + "导入失败"));
            }
            //从业资格证书
            HashMap<String, List<PractitionerCertificate>> practitionerCertificateMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : practitionerCertificateExcels) {
                PractitionerCertificate practitionerCertificate = (PractitionerCertificate) ImportExcelUtil.getEntityByExcelBean((PractitionerCertificateExcelBean) readExcels, new PractitionerCertificate());
                if (practitionerCertificateMap.containsKey(practitionerCertificate.getDef1())) {
                    practitionerCertificateMap.get(practitionerCertificate.getDef1()).add(practitionerCertificate);
                } else {
                    List<PractitionerCertificate> value = new ArrayList<>();
                    value.add(practitionerCertificate);
                    practitionerCertificateMap.put(practitionerCertificate.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<PractitionerCertificate>> entry : practitionerCertificateMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<PractitionerCertificate> oldPractitionerCertificate = practitionerCertificateService.ListByPid(staffFiles.getId());
                        if (oldPractitionerCertificate.size() > 0) {
                            List<Long> ids = oldPractitionerCertificate.parallelStream().map(PractitionerCertificate::getId).collect(Collectors.toList());
                            practitionerCertificateService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        practitionerCertificateService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(practitionerCertificateErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, practitionerCertificateErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, practitionerCertificateErrMsg + "导入失败"));
            }
            //专业技术资格
            HashMap<String, List<TechnicalQualification>> technicalQualificationMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : technicalExcels) {
                TechnicalQualification technicalQualification = (TechnicalQualification) ImportExcelUtil.getEntityByExcelBean((TechnicalQualificationExcelBean) readExcels, new TechnicalQualification());
                if (technicalQualificationMap.containsKey(technicalQualification.getDef1())) {
                    technicalQualificationMap.get(technicalQualification.getDef1()).add(technicalQualification);
                } else {
                    List<TechnicalQualification> value = new ArrayList<>();
                    value.add(technicalQualification);
                    technicalQualificationMap.put(technicalQualification.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<TechnicalQualification>> entry : technicalQualificationMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<TechnicalQualification> oldTechnicalQualification = technicalQualificationService.ListByPid(staffFiles.getId());
                        if (oldTechnicalQualification.size() > 0) {
                            List<Long> ids = oldTechnicalQualification.parallelStream().map(TechnicalQualification::getId).collect(Collectors.toList());
                            technicalQualificationService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        technicalQualificationService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(technicalQualificationErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, technicalQualificationErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, technicalQualificationErrMsg + "导入失败"));
            }
            //近五年三个月以上培训情况
            HashMap<String, List<Train>> trainMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : trainExcels) {
                Train train = (Train) ImportExcelUtil.getEntityByExcelBean((TrainExcelBean) readExcels, new Train());
                if (trainMap.containsKey(train.getDef1())) {
                    trainMap.get(train.getDef1()).add(train);
                } else {
                    List<Train> value = new ArrayList<>();
                    value.add(train);
                    trainMap.put(train.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<Train>> entry : trainMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<Train> oldTrain = trainService.ListByPid(staffFiles.getId());
                        if (oldTrain.size() > 0) {
                            List<Long> ids = oldTrain.parallelStream().map(Train::getId).collect(Collectors.toList());
                            trainService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        trainService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(trainErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, trainErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, trainErrMsg + "导入失败"));
            }
            //侨眷情况
            HashMap<String, List<OverseasMembers>> overseasMembersMap = new HashMap<>();
            //对每条子表数据进行分组
            for (Object readExcels : overseaExcels) {
                OverseasMembers overseasMembers = (OverseasMembers) ImportExcelUtil.getEntityByExcelBean((OverseasMembersExcelBean) readExcels, new OverseasMembers());
                if (overseasMembersMap.containsKey(overseasMembers.getDef1())) {
                    overseasMembersMap.get(overseasMembers.getDef1()).add(overseasMembers);
                } else {
                    List<OverseasMembers> value = new ArrayList<>();
                    value.add(overseasMembers);
                    overseasMembersMap.put(overseasMembers.getDef1(), value);
                }
            }
            //入库
            try {
                for (HashMap.Entry<String, List<OverseasMembers>> entry : overseasMembersMap.entrySet()) {
                    DwhStaffManagement staffFiles = searchStaffByStaffCode(entry.getKey());
                    //覆盖时删除原对应主表记录下属的所有旧子表记录
                    if (isCover) {
                        List<OverseasMembers> oldOverseasMembers = overseasMembersService.ListByPid(staffFiles.getId());
                        if (oldOverseasMembers.size() > 0) {
                            List<Long> ids = oldOverseasMembers.parallelStream().map(OverseasMembers::getId).collect(Collectors.toList());
                            overseasMembersService.deleteLogic(ids);
                        }
                    }
                    entry.getValue().forEach(x -> {
                        x.setStaffFilesId(staffFiles.getId());
                        x.setDef1("");
                        overseasMembersService.saveOrUpdate(x);
                    });
                }
            } catch (Exception e) {
                log.error(overseasMembersErrMsg + "导入失败");
                CacheUtil.put(progress, progress, key, overseasMembersErrMsg + "导入失败");

                return new AsyncResult<>(new ImportResult(false, overseasMembersErrMsg + "导入失败"));
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            log.error("解析失败");
            CacheUtil.put(progress, progress, key, "解析失败");

            return new AsyncResult<>(new ImportResult(false, "解析失败"));
        }
        CacheUtil.put(progress, progress, key, "导入成功");
        return new AsyncResult<>(new ImportResult(true, "导入成功"));
    }

    /**
     * 根据编号加单位查找员工
     *
     * @param staffCode 编号
     * @return 员工
     */
    @Override
    public DwhStaffManagement searchStaffByStaffCode(String staffCode) {
        return getOne(new LambdaQueryWrapper<DwhStaffManagement>().eq(DwhStaffManagement::getStaffCode, EncryptUtil.encryptBase64(staffCode, BASE64_KEY))
                .eq(DwhStaffManagement::getCompanyNameId, TokenUtil.getTokenOrgId()));
    }

    /**
     * 根据身份证加单位查找员工
     *
     * @param documentNumber 身份证
     * @return 员工
     */
    private DwhStaffManagement searchStaffByDocumentNumber(String documentNumber) {
        return getOne(new LambdaQueryWrapper<DwhStaffManagement>().eq(DwhStaffManagement::getDocumentNumber, documentNumber)
                .eq(DwhStaffManagement::getCompanyNameId, TokenUtil.getTokenOrgId()));
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<DwhStaffManagement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DwhStaffManagement::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<DwhStaffManagement> staffFiles = list(queryWrapper);
        List<DwhStaffManagementVO> staffFilesVOS = setVO(staffFiles);
        List<PageData> pageDataList = new ArrayList<>();
        try {
            if (CollectionUtil.isNotEmpty(staffFilesVOS)) {
                for (DwhStaffManagementVO vo : staffFilesVOS) {
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getCompanyName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getCompanyNameId());
                    pd.put("formType", FormTypeConstant.DWH_STAFF_FORM);
                    pd.put("orgName", vo.getCompanyName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.DWH_STAFF_FORM);
    }

    @Override
    public ListResult<DwhStaffManagementVO> getPreList(Query query, QueryWrapper queryWrapper) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
//		queryWrapper.eq("status", FormStatusConstant.FINISH);
        queryWrapper.eq("company_name_id", TokenUtil.getTokenOrgId());
        queryWrapper.eq("def18", 1);
        queryWrapper.eq("is_out", 1);
        IPage<DwhStaffManagement> pages = this.page(Condition.getPage(query), queryWrapper);

        List<DwhStaffManagementVO> staffFilesVOS = setVO(pages.getRecords());

        ListResult<DwhStaffManagementVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    @Override
    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
        try {
            String fname = "员工档案导入模板";
            os = response.getOutputStream();//取得输出流
            response.reset();//清空输出流
            //下面是对中文文件名的处理
            response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
            InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/stafffiles.xlsx");
            fname = java.net.URLEncoder.encode(fname, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("UTF-8"), "UTF-8") + ".xlsx");

            response.setContentType("application/msexcel");//定义输出类型
            int len;
            byte[] b = new byte[2048];
            while ((len = inputStream.read(b)) != -1) {
                os.write(b, 0, len);
            }
            response.setHeader("Content-Length", String.valueOf(inputStream.available()));

            inputStream.close();
            os.close();
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    @Override
    public boolean disable(List<Long> ids) {
        return changeAble(ids, Long.valueOf("2"));
    }

    @Override
    public boolean enable(List<Long> ids) {
        return changeAble(ids, Long.valueOf("1"));
    }

    @Override
    public List<DwhStaffManagement> getByDept(String deptId) {
        LambdaQueryWrapper<DwhStaffManagement> queryWrapper = new LambdaQueryWrapper<>();
        //queryWrapper.eq("def18", 1);
        queryWrapper.eq(DwhStaffManagement::getIsOut, 1);
        queryWrapper.eq(DwhStaffManagement::getCreateCompanyId, TokenUtil.getTokenOrgId());
        if ("企业负责人".equals(deptId)) {
            queryWrapper.eq(DwhStaffManagement::getManagementCategoryId, "027001");
        } else {
            queryWrapper.and(Wrapper -> Wrapper.ne(DwhStaffManagement::getManagementCategoryId, "027001").or().isNull(DwhStaffManagement::getManagementCategoryId));
            queryWrapper.eq(DwhStaffManagement::getDepartmentNameId, deptId);
        }
        return list(queryWrapper);
    }

    @Override
    public String exportImportFile() {
        String key = System.currentTimeMillis() + StringPool.DASH + UUID.randomUUID().toString().replace(StringPool.DASH, "");
        String fileName = key + ".xlsx";
        String exportPath = environment.getProperty("excel.path");

        /**
         * 导出路径不存在则创建
         */
        File file = new File(exportPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/dwhStaffMangementExport.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(exportPath + fileName).withTemplate(inputStream).build();

        // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
        // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
        // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存

        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        // 表二
        WriteSheet staffFilesWriteSheet = EasyExcel.writerSheet(1).build();

        Query query = new Query();
        query.setFlag(1);
        QueryWrapper<DwhStaffManagement> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new DwhStaffManagement()), query.getSearch()
        );
        TokenSearch<DwhStaffManagement> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);
        queryWrapper.lambda().eq(DwhStaffManagement::getDef18, 1);
        queryWrapper.lambda().eq(DwhStaffManagement::getIsOut, 1);
        queryWrapper.lambda().orderByAsc(DwhStaffManagement::getDepartmentCode);
        queryWrapper.lambda().orderByAsc(DwhStaffManagement::getOrderNumber);
        queryWrapper.lambda().orderByDesc(DwhStaffManagement::getCreateTime);
        queryWrapper.lambda().orderByDesc(DwhStaffManagement::getId);

        List<DwhStaffManagementVO> staffFilesVOS = dwhStaffManagementWrapper.entityToVO(list(queryWrapper));
        staffFilesVOS.forEach(e ->{
            if (null != e.getIsReserveCadre() && 2 == e.getIsReserveCadre()) {
                e.setIsReserveCadreName("是");
            } else {
                e.setIsReserveCadreName("否");
            }
            if (null != e.getIsCorporateTalent() && 2 == e.getIsCorporateTalent()) {
                e.setIsCorporateTalentName("是");
            } else {
                e.setIsCorporateTalentName("否");
            }
        });
        excelWriter.fill(staffFilesVOS, fillConfig, staffFilesWriteSheet);

        List<Long> staffFilesIds = staffFilesVOS.stream().map(DwhStaffManagementVO::getId).collect(Collectors.toList());

        Map<Long, List<AppointRemoveVO>> appointRemoveVOMap;
        Map<Long, List<EducationDegreeVO>> educationDegreeVOMap;
        Map<Long, List<RewardsPunishmentsVO>> rewardsPunishmentsVOMap;
        Map<Long, List<AnnualAssessmentVO>> annualAssessmentVOMap;
        Map<Long, List<SocialRelationsVO>> socialRelationsVOMap;
        Map<Long, List<PractitionerCertificateVO>> practitionerCertificateVOMap;
        Map<Long, List<TechnicalQualificationVO>> technicalQualificationVOMap;
        Map<Long, List<TrainVO>> trainVOMap;
        Map<Long, List<OverseasMembersVO>> overseasMembersVOMap;
        if(CollectionUtil.isEmpty(staffFilesIds)){
            appointRemoveVOMap = new HashMap<>();
            educationDegreeVOMap = new HashMap<>();
            rewardsPunishmentsVOMap = new HashMap<>();
            annualAssessmentVOMap = new HashMap<>();
            socialRelationsVOMap = new HashMap<>();
            practitionerCertificateVOMap = new HashMap<>();
            technicalQualificationVOMap = new HashMap<>();
            trainVOMap = new HashMap<>();
            overseasMembersVOMap = new HashMap<>();
        }else {
            // 任免记录 3
            appointRemoveVOMap = appointRemoveWrapper
                    .entityToVO(appointRemoveService.list(new LambdaQueryWrapper<AppointRemove>()
                            .in(AppointRemove::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(AppointRemoveVO::getStaffFilesId));

            // 学历学位
            List<EducationDegreeVO> eduVoList = educationDegreeWrapper.entityToVO(educationDegreeService.list(new LambdaQueryWrapper<EducationDegree>()
                    .in(EducationDegree::getStaffFilesId, staffFilesIds)));
            eduVoList.forEach(e ->{
                if (null != e.getIsHighestEducational() && 2 == e.getIsHighestEducational()) {
                    e.setIsHighestEducationalName("是");
                } else {
                    e.setIsHighestEducationalName("否");
                }
                if (null != e.getIsHighestDegree() && 2 == e.getIsHighestDegree()) {
                    e.setIsHighestDegreeName("是");
                } else {
                    e.setIsHighestDegreeName("否");
                }
            });
            educationDegreeVOMap = eduVoList
                    .stream().collect(Collectors.groupingBy(EducationDegreeVO::getStaffFilesId));

            // 奖惩情况
            rewardsPunishmentsVOMap = rewardsPunishmentsWrapper
                    .entityToVO(rewardsPunishmentsService.list(new LambdaQueryWrapper<RewardsPunishments>()
                            .in(RewardsPunishments::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(RewardsPunishmentsVO::getStaffFilesId));

            // 年度考核结果
            annualAssessmentVOMap = annualAssessmentWrapper
                    .entityToVO(annualAssessmentService.list(new LambdaQueryWrapper<AnnualAssessment>()
                            .in(AnnualAssessment::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(AnnualAssessmentVO::getStaffFilesId));

            // 家庭及社会关系
            socialRelationsVOMap = socialRelationsWrapper
                    .entityToVO(socialRelationsService.list(new LambdaQueryWrapper<SocialRelations>()
                            .in(SocialRelations::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(SocialRelationsVO::getStaffFilesId));

            // 从业资格证书
            practitionerCertificateVOMap = practitionerCertificateWrapper
                    .entityToVO(practitionerCertificateService.list(new LambdaQueryWrapper<PractitionerCertificate>()
                            .in(PractitionerCertificate::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(PractitionerCertificateVO::getStaffFilesId));

            // 专业技术资格
            technicalQualificationVOMap = technicalQualificationWrapper
                    .entityToVO(technicalQualificationService.list(new LambdaQueryWrapper<TechnicalQualification>()
                            .in(TechnicalQualification::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(TechnicalQualificationVO::getStaffFilesId));

            // 近五年三月以上培训情况
            trainVOMap = trainWrapper
                    .entityToVO(trainService.list(new LambdaQueryWrapper<Train>()
                            .in(Train::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(TrainVO::getStaffFilesId));

            // 侨眷情况
            overseasMembersVOMap = overseasMembersWrapper
                    .entityToVO(overseasMembersService.list(new LambdaQueryWrapper<OverseasMembers>()
                            .in(OverseasMembers::getStaffFilesId, staffFilesIds)))
                    .stream().collect(Collectors.groupingBy(OverseasMembersVO::getStaffFilesId));
        }


        List<EducationDegreeVO> educationDegreeVOS = new ArrayList<>();
        List<AppointRemoveVO> appointRemoveVOS = new ArrayList<>();
        List<RewardsPunishmentsVO> rewardsPunishmentsVOS = new ArrayList<>();
        List<AnnualAssessmentVO> annualAssessmentVOS = new ArrayList<>();
        List<SocialRelationsVO> socialRelationsVOS = new ArrayList<>();
        List<PractitionerCertificateVO> practitionerCertificateVOS = new ArrayList<>();
        List<TechnicalQualificationVO> technicalQualificationVOS = new ArrayList<>();
        List<TrainVO> trainVOS = new ArrayList<>();
        List<OverseasMembersVO> overseasMembersVOS = new ArrayList<>();

        for (DwhStaffManagementVO staffFilesVO : staffFilesVOS) {
            Long staffFilesId = staffFilesVO.getId();
            String staffCode = staffFilesVO.getStaffCode();
            if (educationDegreeVOMap.containsKey(staffFilesId)) {
                educationDegreeVOS.addAll(educationDegreeVOMap.get(staffFilesId).stream()
                        .map(educationDegreeVO -> {
                            educationDegreeVO.setStaffCode(staffCode);
                            return educationDegreeVO;
                        }).collect(Collectors.toList()));
            }

            if (appointRemoveVOMap.containsKey(staffFilesId)) {
                appointRemoveVOS.addAll(appointRemoveVOMap.get(staffFilesId).stream()
                        .map(appointRemoveVO -> {
                            appointRemoveVO.setStaffCode(staffCode);
                            return appointRemoveVO;
                        }).collect(Collectors.toList()));
            }

            if (rewardsPunishmentsVOMap.containsKey(staffFilesId)) {
                rewardsPunishmentsVOS.addAll(rewardsPunishmentsVOMap.get(staffFilesId).stream()
                        .map(rewardsPunishmentsVO -> {
                            rewardsPunishmentsVO.setStaffCode(staffCode);
                            return rewardsPunishmentsVO;
                        }).collect(Collectors.toList()));
            }

            if (annualAssessmentVOMap.containsKey(staffFilesId)) {
                annualAssessmentVOS.addAll(annualAssessmentVOMap.get(staffFilesId).stream()
                        .map(annualAssessmentVO -> {
                            annualAssessmentVO.setStaffCode(staffCode);
                            return annualAssessmentVO;
                        }).collect(Collectors.toList()));
            }

            if (socialRelationsVOMap.containsKey(staffFilesId)) {
                socialRelationsVOS.addAll(socialRelationsVOMap.get(staffFilesId).stream()
                        .map(socialRelationsVO -> {
                            socialRelationsVO.setStaffCode(staffCode);
                            return socialRelationsVO;
                        }).collect(Collectors.toList()));
            }

            if (practitionerCertificateVOMap.containsKey(staffFilesId)) {
                practitionerCertificateVOS.addAll(practitionerCertificateVOMap.get(staffFilesId).stream()
                        .map(practitionerCertificateVO -> {
                            practitionerCertificateVO.setStaffCode(staffCode);
                            return practitionerCertificateVO;
                        }).collect(Collectors.toList()));
            }

            if (technicalQualificationVOMap.containsKey(staffFilesId)) {
                technicalQualificationVOS.addAll(technicalQualificationVOMap.get(staffFilesId).stream()
                        .map(technicalQualificationVO -> {
                            technicalQualificationVO.setStaffCode(staffCode);
                            return technicalQualificationVO;
                        }).collect(Collectors.toList()));
            }

            if (trainVOMap.containsKey(staffFilesId)) {
                trainVOS.addAll(trainVOMap.get(staffFilesId).stream()
                        .map(trainVO -> {
                            trainVO.setStaffCode(staffCode);
                            return trainVO;
                        }).collect(Collectors.toList()));
            }

            if (overseasMembersVOMap.containsKey(staffFilesId)) {
                overseasMembersVOS.addAll(overseasMembersVOMap.get(staffFilesId).stream()
                        .map(overseasMembersVO -> {
                            overseasMembersVO.setStaffCode(staffCode);
                            return overseasMembersVO;
                        }).collect(Collectors.toList()));
            }

        }


        WriteSheet appointRemoveWriteSheet = EasyExcel.writerSheet(3).build();
        excelWriter.fill(appointRemoveVOS, fillConfig, appointRemoveWriteSheet);
        WriteSheet educationDegreeWriteSheet = EasyExcel.writerSheet(4).build();
        excelWriter.fill(educationDegreeVOS, fillConfig, educationDegreeWriteSheet);
        WriteSheet rewardsPunishmentsWriteSheet = EasyExcel.writerSheet(5).build();
        excelWriter.fill(annualAssessmentVOS, fillConfig, rewardsPunishmentsWriteSheet);
        WriteSheet annualAssessmentWriteSheet = EasyExcel.writerSheet(6).build();
        excelWriter.fill(annualAssessmentVOS, fillConfig, annualAssessmentWriteSheet);
        WriteSheet socialRelationsWriteSheet = EasyExcel.writerSheet(7).build();
        excelWriter.fill(socialRelationsVOS, fillConfig, socialRelationsWriteSheet);
        WriteSheet practitionerCertificateWriteSheet = EasyExcel.writerSheet(8).build();
        excelWriter.fill(practitionerCertificateVOS, fillConfig, practitionerCertificateWriteSheet);
        WriteSheet technicalQualificationWriteSheet = EasyExcel.writerSheet(9).build();
        excelWriter.fill(technicalQualificationVOS, fillConfig, technicalQualificationWriteSheet);
        WriteSheet trainWriteSheet = EasyExcel.writerSheet(10).build();
        excelWriter.fill(trainVOS, fillConfig, trainWriteSheet);
        WriteSheet overseasMembersWriteSheet = EasyExcel.writerSheet(11).build();
        excelWriter.fill(overseasMembersVOS, fillConfig, overseasMembersWriteSheet);
        excelWriter.finish();

        PageData org = orgzationService.getCompanyNameById(TokenUtil.getTokenOrgId());
        String companyName = "";
        if (org != null) {
            companyName = org.getString("name");
        }
        String excelName = companyName + "_党委会档案备份";
        fileNameMap.put(key, excelName);
        return key;
    }

    @Override
    public void download(String key, HttpServletResponse response) {
        if (!fileNameMap.containsKey(key)) {
            log.error("BaseInvestmentPlanServiceImpl 导出excel失败--------> key " + key);
            return;
        }
        String excelName = fileNameMap.get(key);
        String excelPath = environment.getProperty("excel.path") + "/" + key + ".xlsx";
        FileTools.exportExcel(excelPath, excelName, response);
        fileNameMap.remove(key);
    }

    @Override
    public DwhStaffManagementVO getDetailVO(Object id) {
        DwhStaffManagementVO staffFilesVO = dwhStaffManagementWrapper.entityToVO(getById(Long.valueOf(String.valueOf(id))));
        setChild(staffFilesVO);
        return staffFilesVO;
    }

    @Override
    public Integer getIsChange(Long id, String month) {

        String nextMonth = DateUtil.format(DateUtil.plusMonths(DateUtil.parse(month, DateUtil.PATTERN_MONTH), 1), DateUtil.PATTERN_MONTH);
        List<FormHistoryRecord> historyRecords = formHistoryRecordService
                .list(new LambdaQueryWrapper<FormHistoryRecord>().eq(FormHistoryRecord::getRecordId, id)
                        .le(FormHistoryRecord::getCreateTime, nextMonth + "-01 00:00:00").orderByDesc(FormHistoryRecord::getVersion));

        if (CollectionUtil.isEmpty(historyRecords)) {
            return 1;
        }

        List<DwhStaffManagement> records = new ArrayList<>();
        for (int i = 0; i < historyRecords.size(); i++) {
            FormHistoryRecord formHistoryRecord = historyRecords.get(i);
            String updateTime = DateUtil.format(formHistoryRecord.getCreateTime(), DateUtil.PATTERN_MONTH);
            try {
                DwhStaffManagement record = JSON.parseObject(formHistoryRecord.getRecord(), DwhStaffManagement.class);
                if (updateTime.equals(month)) {
                    records.add(record);
                } else {
                    records.add(record);
                    break;
                }
            } catch (Exception e) {
                log.error("解析json失败" + ExceptionUtils.getFullStackTrace(e));
                log.error("record--->" + formHistoryRecord.getRecord());
            }

        }

        if (CollectionUtil.isEmpty(records)) {
            return 1;
        }
        if (month.equals(DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH))) {
            records.add(getById(id));
        }

        for (DwhStaffManagement newRecord : records) {
            for (DwhStaffManagement oldRecord : records) {
                if (!newRecord.getManagementCategoryId().equals(oldRecord.getManagementCategoryId())) {
                    return 2;
                }
            }
        }

        return 1;
    }

    private boolean changeAble(List<Long> ids, Long ableStatus) {
        LambdaUpdateWrapper<DwhStaffManagement> updateWrapper = new LambdaUpdateWrapper<>();
        return update(updateWrapper.in(DwhStaffManagement::getId, ids).set(DwhStaffManagement::getDef18, ableStatus));
    }

    @Override
    public DwhStaffManagement searchStaffByExcelCode(String excelCode) {
        return baseMapper.searchStaffByExcelCode(excelCode).get(0);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveOrUpdate(DwhStaffManagement staffFiles) {
        if (staffFiles.getStatus() == null) {
            staffFiles.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (StringUtil.isBlank(staffFiles.getVersion())) {
            staffFiles.setVersion("1");
        }
        if (staffFiles.getId() == null) {
            staffFiles.setDef18(Long.valueOf("1"));
            staffFiles.setFormType(String.valueOf(FormTypeConstant.DWH_STAFF_FORM));
            staffFiles.setCode(formCodeService.getCode(FormTypeConstant.DWH_STAFF_FORM));
            if (!Optional.ofNullable(staffFiles.getIsOut()).isPresent()) {
                staffFiles.setIsOut(1);
            }
        }

        if (!Optional.ofNullable(staffFiles.getOrderNumber()).isPresent()) {
            staffFiles.setOrderNumber(9999);
        }

        // 保存部门编码 用于list接口排序
        if (Optional.ofNullable(staffFiles.getDepartmentNameId()).isPresent()) {
            Dept dept = deptService.getById(staffFiles.getDepartmentNameId());
            if (Optional.ofNullable(dept).isPresent()) {
                staffFiles.setStaffCode(dept.getDeptCode());
            }
        }
        staffFiles.setStaffCode(staffFiles.getDocumentNumber());
        boolean result = super.saveOrUpdate(staffFiles);
        StaffCache.update(staffFiles.getId());
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            DwhStaffManagement staffFiles = getById(id);
            if (staffFiles == null) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }

        boolean result = super.deleteLogic(ids);
        if (result) {
            appointRemoveService.deleteLogicStaffFilesId(ids);
            educationDegreeService.deleteLogicStaffFilesId(ids);
            workExperienceService.deleteLogicStaffFilesId(ids);
            rewardsPunishmentsService.deleteLogicStaffFilesId(ids);
            annualAssessmentService.deleteLogicStaffFilesId(ids);
            socialRelationsService.deleteLogicStaffFilesId(ids);
            practitionerCertificateService.deleteLogicStaffFilesId(ids);
            technicalQualificationService.deleteLogicStaffFilesId(ids);
            trainService.deleteLogicStaffFilesId(ids);
            overseasMembersService.deleteLogicStaffFilesId(ids);
        }
        StaffCache.evictBatch(ids);
        return result;
    }

    @Override
    public HashMap<String, Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String, Object>();
    }

    @Override
    public Boolean finish(String id) {
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public String checkIsExisted(Long id, String code, String companyNameId) {
        if (StringUtil.isNotBlank(code)) {
            DwhStaffManagement staffFiles = getOne(new LambdaQueryWrapper<DwhStaffManagement>().eq(DwhStaffManagement::getStaffCode, code).eq(DwhStaffManagement::getCompanyNameId, companyNameId));
            if (Optional.ofNullable(staffFiles).isPresent()) {
                if (id == null || !id.equals(staffFiles.getId())) {
                    return "人员编码已存在";
                }
            }
        }

        return null;
    }

    @Override
    public boolean checkDocumentNumber(Long id, String companyNameId, String documentNumber) {
        LambdaQueryWrapper<DwhStaffManagement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DwhStaffManagement::getCompanyNameId, companyNameId);
        queryWrapper.eq(DwhStaffManagement::getDocumentNumber, documentNumber);
        if (Optional.ofNullable(getOne(queryWrapper)).isPresent()) {
            if (id == null || !id.equals(getOne(queryWrapper).getId())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id           主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            DwhStaffManagement staffFiles = getById(id);

            if (updateStatus == FormStatusConstant.FINISH) {
                staffFiles.setApprovedUser(TokenUtil.getTokenUserId());
                staffFiles.setApprovedTime(DateUtil.now());
            }
            staffFiles.setStatus(updateStatus);
            updateById(staffFiles);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

//	/**
//	 * 员工档案变更
//	 * @param staffFilesVO 员工档案对象
//	 * @return
//	 */
//	@Override
//	public Boolean change(StaffFilesVO staffFilesVO) {
//
//		//储存旧数据
//		StaffFiles staffFilesOld= StaffFilesCache.getById(staffFilesVO.getId());
//		StaffFilesVO staffFilesOldVO = setChild(StaffFilesWrapper.build().entityVO(staffFilesOld));
//		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(staffFilesOldVO));
//		snapshotClient.push("PersonnelStaffFiles",staffFilesVO.getId(),jsonObject);
//		if (StringUtil.isEmpty(staffFilesVO.getVersion())) {
//			staffFilesVO.setVersion("1");
//		} else {
//			staffFilesVO.setVersion(String.valueOf(Integer.parseInt(staffFilesVO.getVersion())+1));
//		}
//		staffFilesVO.setUpdateTime(new Date());
//		saveChild(staffFilesVO);
//		UpdateWrapper<StaffFiles> updateWrapper = new UpdateWrapper<>();
//		if(staffFilesVO.getIsBoardOfDirectors()!=null && staffFilesVO.getIsBoardOfDirectors()==1){
//			update(staffFilesVO, updateWrapper.eq("id", staffFilesVO.getId()).set("directorship_id", null));
//		}
//		if(staffFilesVO.getIsBoardOfSupervisors()!=null && staffFilesVO.getIsBoardOfSupervisors()==1){
//			update(staffFilesVO, updateWrapper.eq("id", staffFilesVO.getId()).set("supervisor_position_id", null));
//		}
//		Boolean result = update(staffFilesVO,updateWrapper.eq("id",staffFilesVO.getId()));
//		if(result){
//			JSONObject json = new JSONObject();
//			json.put("id",staffFilesVO.getId());
//			json.put("name",staffFilesVO.getStaffName());
//			json.put("phone",staffFilesVO.getWorkPhone());
//			json.put("email",staffFilesVO.getEmail());
//			json.put("orgId",staffFilesVO.getCompanyNameId());
//			json.put("deptId",staffFilesVO.getDepartmentNameId());
//			rabbitTemplate.convertAndSend("person2user-data",json);
//		}
//		return result;
//	}

    @Override
    public ReportReturnVO report(DwhStaffManagementDTO staffFilesDTO) {
        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();

        reportVO
                .addHeader(HeaderVO.builder().key("companyName").title("单位").build())
                .addHeader(HeaderVO.builder().key("staffName").title("姓名").build())
                .addHeader(HeaderVO.builder().key("jobNameId").title("职务").build())
                .addHeader(HeaderVO.builder().key("genderName").title("性别").build())
                .addHeader(HeaderVO.builder().key("birthday").title("出生日期").build())
                .addHeader(HeaderVO.builder().key("nationName").title("民族").build())
                .addHeader(HeaderVO.builder().key("politicCountenanceName").title("政治面貌").build())
                .addHeader(HeaderVO.builder().key("staffCategoryName").title("人员类别").build())
                .addHeader(HeaderVO.builder().key("talentCategory").title("人才类别").build())
                .addHeader(HeaderVO.builder().key("nativePlace").title("籍贯").build())
                .addHeader(HeaderVO.builder().key("birthPlace").title("出生地").build())
                .addHeader(HeaderVO.builder().key("workTime").title("参加工作时间").build())
                .addHeader(HeaderVO.builder().key("technicalPosition").title("专业技术职称").build())
                .addHeader(HeaderVO.builder().key("educationalName").title("最高学历").build())
                .addHeader(HeaderVO.builder().key("degreeName").title("最高学位").build())
                .addHeader(HeaderVO.builder().key("staffCode").title("身份证号").build())
        ;

        List<DwhStaffManagement> staffFiles = baseMapper.reportDataPage(staffFilesDTO.getCompanyNameIds(), staffFilesDTO.getStaffName(), staffFilesDTO.getGenderIds(), staffFilesDTO.getJobNameId(),
                staffFilesDTO.getEducationalIds(), staffFilesDTO.getTechnicalPosition(), staffFilesDTO.getCompanyInitiationTimeStart(), staffFilesDTO.getCompanyInitiationTimeEnd(),
                staffFilesDTO.getWorkTimeStart(), staffFilesDTO.getWorkTimeEnd(), staffFilesDTO.getPoliticCountenanceIds(),
                staffFilesDTO.getIsReserveCadre(), staffFilesDTO.getIsCorporateTalent(), staffFilesDTO.getManagementCategoryIds());
        if (CollectionUtil.isNotEmpty(staffFiles)) {

            List<DwhStaffManagementVO> list = setVO(staffFiles);
//			List<StaffFilesVO> list = staffFilesWrapper.entityToVO(staffFiles);

            //给所有数据按照单位编码升序，人员编码升序
            list = list.parallelStream().filter(staffFilesVO -> StringUtil.isNotBlank(staffFilesVO.getCompanyCode()))
                    .sorted(Comparator.comparing(DwhStaffManagementVO::getCompanyCode)).collect(Collectors.toList());
            List<DwhStaffManagementVO> list2 = new ArrayList<>();
            String companyNameSearchId = "";
            int count = 0;
            int sum = 0;
            for (int i = 0; i < list.size(); i++) {
                if (!companyNameSearchId.equals(list.get(i).getCompanyNameId())) {
                    if (i > 0) {
                        DwhStaffManagementVO Total = new DwhStaffManagementVO();
                        Total.setCompanyName("小计：" + count);
                        list2.add(Total);
                        sum += count;
                    }
                    companyNameSearchId = list.get(i).getCompanyNameId();
                    count = 1;
                } else {
                    count++;
                }
                list2.add(list.get(i));
            }
            sum += count;
            DwhStaffManagementVO LastTotal = new DwhStaffManagementVO();
            LastTotal.setCompanyName("小计：" + count);
            list2.add(LastTotal);

            DwhStaffManagementVO SumTotal = new DwhStaffManagementVO();
            SumTotal.setCompanyName("总计：" + sum);
            list2.add(SumTotal);

            reportVO.setData(list2);
        }

        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public ReportReturnVO reportChartsGender(Long companyNameId) {
        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();
        reportVO.addHeader(HeaderVO.builder().key("name").title("性别").build());

        JSONArray jsonArray = new JSONArray();
        List<DwhStaffManagementChartsVO> list = baseMapper.reportChartsGender(companyNameId);
        list.parallelStream().forEach(staffFilesChartsVO -> {
//			staffFilesChartsVO.setDataName(Optional.ofNullable(GenderCache.getById(staffFilesChartsVO.getDataCode())).map((x)->x.getGenderName()).orElse(""));
            jsonArray.add(staffFilesChartsVO);
        });
        reportReturnVO.setCharts(jsonArray);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public ReportReturnVO reportChartsPoliticCountenance(Long companyNameId) {
        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();
        reportVO.addHeader(HeaderVO.builder().key("name").title("政治面貌").build());

        JSONArray jsonArray = new JSONArray();
        List<DwhStaffManagementChartsVO> list = baseMapper.reportChartsPoliticCountenance(companyNameId);
        list.parallelStream().forEach(staffFilesChartsVO -> {
//			staffFilesChartsVO.setDataName(Optional.ofNullable(PoliticCountenanceCache.getById(staffFilesChartsVO.getDataCode())).map((x)->x.getPoliticCountenanceName()).orElse(""));
            jsonArray.add(staffFilesChartsVO);
        });
        reportReturnVO.setCharts(jsonArray);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public ReportReturnVO reportChartsEducational(Long companyNameId) {
        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();
        reportVO.addHeader(HeaderVO.builder().key("name").title("最高学历").build());

        JSONArray jsonArray = new JSONArray();
        List<DwhStaffManagementChartsVO> list = baseMapper.reportChartsEducational(companyNameId);
        list.parallelStream().forEach(staffFilesChartsVO -> {
//			staffFilesChartsVO.setDataName(Optional.ofNullable(EducationalCache.getById(staffFilesChartsVO.getDataCode())).map((x)->x.getEducationalName()).orElse(""));
            jsonArray.add(staffFilesChartsVO);
        });
        reportReturnVO.setCharts(jsonArray);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public ReportReturnVO reportChartsWorkTime(Long companyNameId) {
        HashMap<Long, String> map = new HashMap();
        map.put(0L, "未填写数据");
        map.put(1L, "5年及以下");
        map.put(2L, "5年-10年");
        map.put(3L, "10年-20年");
        map.put(4L, "20年-30年");
        map.put(5L, "30年以上");

        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();
        reportVO.addHeader(HeaderVO.builder().key("name").title("参加工作时间").build());

        JSONArray jsonArray = new JSONArray();
        List<DwhStaffManagementChartsVO> list = baseMapper.reportChartsWorkTime(companyNameId);
        list.parallelStream().forEach(staffFilesChartsVO -> {
            staffFilesChartsVO.setDataName(map.get(staffFilesChartsVO.getDataCode()));
            jsonArray.add(staffFilesChartsVO);
        });
        reportReturnVO.setCharts(jsonArray);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public DwhStaffManagementVO setChild(DwhStaffManagementVO staffFilesVO) {
        if (!Optional.ofNullable(staffFilesVO).isPresent()) {
            return null;
        }
        staffFilesVO.setAppointRemoveVO(appointRemoveWrapper.entityToVO(appointRemoveService
                .list(new LambdaQueryWrapper<AppointRemove>().eq(AppointRemove::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setWorkExperienceVO(workExperienceWrapper.entityToVO(workExperienceService
                .list(new LambdaQueryWrapper<WorkExperience>().eq(WorkExperience::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setRewardsPunishmentsVO(rewardsPunishmentsWrapper.entityToVO(rewardsPunishmentsService
                .list(new LambdaQueryWrapper<RewardsPunishments>().eq(RewardsPunishments::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setAnnualAssessmentVO(annualAssessmentWrapper.entityToVO(annualAssessmentService
                .list(new LambdaQueryWrapper<AnnualAssessment>().eq(AnnualAssessment::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setEducationDegreeVO(educationDegreeWrapper.entityToVO((educationDegreeService
                .list(new LambdaQueryWrapper<EducationDegree>().eq(EducationDegree::getStaffFilesId, staffFilesVO.getId())))));
        staffFilesVO.setSocialRelationsVO(socialRelationsWrapper.entityToVO(socialRelationsService
                .list(new LambdaQueryWrapper<SocialRelations>().eq(SocialRelations::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setPractitionerCertificateVO(practitionerCertificateWrapper.entityToVO(practitionerCertificateService
                .list(new LambdaQueryWrapper<PractitionerCertificate>().eq(PractitionerCertificate::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setTechnicalQualificationVO(technicalQualificationWrapper.entityToVO(technicalQualificationService
                .list(new LambdaQueryWrapper<TechnicalQualification>().eq(TechnicalQualification::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setTrainVO(trainWrapper.entityToVO(trainService
                .list(new LambdaQueryWrapper<Train>().eq(Train::getStaffFilesId, staffFilesVO.getId()))));
        staffFilesVO.setOverseasMembersVO(overseasMembersWrapper.entityToVO(overseasMembersService
                .list(new LambdaQueryWrapper<OverseasMembers>().eq(OverseasMembers::getStaffFilesId, staffFilesVO.getId()))));
        return staffFilesVO;
    }

    private List<Long> getByDocumentNumber(String documentNumber) {
        LambdaQueryWrapper<DwhStaffManagement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DwhStaffManagement::getDocumentNumber, documentNumber);
        List<DwhStaffManagement> list = list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return list.stream().map(DwhStaffManagement::getId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> getByStaffId(Long id) {
        DwhStaffManagement staffFiles = getById(id);
        if (Optional.ofNullable(staffFiles).isPresent()) {
            return getByDocumentNumber(staffFiles.getDocumentNumber());
        }
        return new ArrayList<>();
    }

    @Override
    public R<DwhStaffManagementVO> getDetailObj(DwhStaffManagementVO staffFilesVO) {
        if (!Optional.ofNullable(staffFilesVO).isPresent()) {
            return new R(CommonCode.FAIL);
        }
        staffFilesVO.setPartTimeJobSituation(partTimeInfoService.getPartTimeJobSituation(getByDocumentNumber(staffFilesVO.getDocumentNumber())));

        staffFilesVO.setPartTimeInfos(partTimeInfoService.getPartTimeInfosByStatus(staffFilesVO.getId(), PartTimeStatus.INCUMBENCY.getStatus()));
        setChild(staffFilesVO);

        R<DwhStaffManagementVO> objResult = new R<>(CommonCode.SUCCESS);
        objResult.setPageData(staffFilesVO);
        return objResult;
    }

    @Override
    public R<ReportReturnVO> getReportObj(ReportReturnVO reportReturnVO) {
        return R.data(reportReturnVO);
    }

    @Override
    public File buildpdf(Long id) {
        DwhStaffManagementVO bean = dwhStaffManagementWrapper.entityToVO(getById(id));
        Map<String, String> images = new HashMap<>(16);
        File file = null;

        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            InputStream inputStream = resourceLoader.getResource("/pdf/staff.pdf").getInputStream();
            //通过将文件转换为临时文件进行操作
            File model = File.createTempFile("model", ".png");
            try {
                FileUtils.copyInputStreamToFile(inputStream, model);
            } finally {
                //关闭IO
                IOUtils.closeQuietly(inputStream);
            }


            if (bean != null && model.exists()) {
                Map<String, Object> data = OutPdf.beanToMap(bean);
                data.put("birthday", processDate2((Date) data.get("birthday")));
                data.put("joinPartyTime", data.get("politicCountenanceName") + "\n" + processDate((Date) data.get("joinPartyTime")));
                List<EducationDegreeVO> temp = educationDegreeWrapper.entityToVO(educationDegreeService
                        .list(new LambdaQueryWrapper<EducationDegree>().eq(EducationDegree::getStaffFilesId, bean.getId()).orderByAsc(EducationDegree::getStartDate)));

                temp.forEach(x -> {
                    if ("全日制教育".equals(x.getEducationTypeName())) {
                        data.put("educationalName1", StringUtil.isEmpty(x.getEducationalName()) ? "" : ("学历：" + x.getEducationalName()));
                        data.put("degreeName1", StringUtil.isEmpty(x.getDegreeName()) ? "" : ("学位：" + x.getDegreeName()));
                        data.put("schoolDepartmentMajor1", x.getSchoolDepartmentMajor());
                    } else if ("在职教育".equals(x.getEducationTypeName())) {
                        data.put("educationalName2", StringUtil.isEmpty(x.getEducationalName()) ? "" : ("学历：" + x.getEducationalName()));
                        data.put("degreeName2", StringUtil.isEmpty(x.getDegreeName()) ? "" : ("学位：" + x.getDegreeName()));
                        data.put("schoolDepartmentMajor2", x.getSchoolDepartmentMajor());
                    }
                });

                List<SocialRelationsVO> temp2 = socialRelationsWrapper.entityToVO(socialRelationsService
                        .list(new LambdaQueryWrapper<SocialRelations>().eq(SocialRelations::getStaffFilesId, bean.getId())));
                for (int x = 0; x < temp2.size(); x++) {
                    data.put("relations.appellation." + x, temp2.get(x).getAppellation());
                    data.put("relations.fullName." + x, temp2.get(x).getFullName());
                    data.put("relations.birthday." + x, temp2.get(x).getBirthday());
                    data.put("relations.politicCountenanceName." + x, temp2.get(x).getPoliticCountenanceName());
                    data.put("relations.workUnitAndjobNameName." + x, (temp2.get(x).getWorkUnit() == null ? "" : temp2.get(x).getWorkUnit()) + (temp2.get(x).getJobNameId() == null ? "" : temp2.get(x).getJobNameId()));

                }
                List<RewardsPunishmentsVO> temp3 = rewardsPunishmentsWrapper.entityToVO(rewardsPunishmentsService
                        .list(new LambdaQueryWrapper<RewardsPunishments>().eq(RewardsPunishments::getStaffFilesId, bean.getId()).orderByAsc(RewardsPunishments::getRewardDate)));

                temp3.forEach(x -> {
                    data.put("rewardsPunishments", (data.get("rewardsPunishments") == null ? "" : data.get("rewardsPunishments")) + processDate(x.getRewardDate()) + "  获得 " + x.getGrantingUnitName() + " 授予的 " + x.getHonorAwardName() + "荣誉\n");
                });

                String fileName = model.getPath();
                PdfReader reader = new PdfReader(fileName);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                /* 将要生成的目标PDF文件名称 */
                PdfStamper ps = new PdfStamper(reader, bos);
                /* 使用中文字体 */
                BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                ArrayList<BaseFont> fontList = new ArrayList<>();
                fontList.add(bf);

                /* 取出报表模板中的所有字段 */
                AcroFields fields = ps.getAcroFields();
                fields.setSubstitutionFonts(fontList);
                for (String key : data.keySet()) {
                    String value = data.get(key).toString();
                    if (data.get(key) instanceof Date) {
                        value = processDate((Date) data.get(key));
                    }
                    fields.setField(key, value);
                }
                if (images != null) {
                    for (String key : images.keySet()) {
                        if (!StringUtil.isEmpty(images.get(key))) {
                            //待加入图片的文字域,设置为隐藏;不然会遮挡掉图片的
                            OutPdf.insertImage(fields, ps, key, images.get(key));
                        }
                    }
                }
                /* 必须要调用这个，否则文档不会生成的 */
                ps.setFormFlattening(true);
                ps.close();
                File dir = new File(model.getParent());
                String classFullName = bean.getClass().getName();
                file = File.createTempFile(classFullName.substring(classFullName.lastIndexOf(".")), ".pdf", dir);
                OutputStream fos = new FileOutputStream(file);
                fos.write(bos.toByteArray());
                fos.flush();
                fos.close();
                bos.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    private static String processDate(Date date) {
        return date == null ? "" : DateUtil.format(date, DateUtil.PATTERN_DATE);
    }

    private static String processDate2(Date date) {
        return date == null ? "" : DateUtil.format(date, DateUtil.PATTERN_MONTH);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean saveChild(DwhStaffManagementVO staffFilesVO) {
        //学历学位
        try {
            List<EducationDegreeVO> educationDegreeVO = staffFilesVO.getEducationDegreeVO();
            if (CollectionUtil.isNotEmpty(educationDegreeVO)) {
                for (EducationDegreeVO one : educationDegreeVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        educationDegreeService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        educationDegreeService.saveOrUpdate(one);
                    }
                }
            }

            //任免记录
            List<AppointRemoveVO> appointRemoveVO = staffFilesVO.getAppointRemoveVO();
            if (CollectionUtil.isNotEmpty(appointRemoveVO)) {
                for (AppointRemoveVO one : appointRemoveVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        appointRemoveService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        appointRemoveService.saveOrUpdate(one);
                    }
                }
            }
            //工作经历
            List<WorkExperienceVO> workExperienceVO = staffFilesVO.getWorkExperienceVO();
            if (CollectionUtil.isNotEmpty(workExperienceVO)) {
                for (WorkExperienceVO one : workExperienceVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        workExperienceService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        workExperienceService.saveOrUpdate(one);
                    }
                }
            }
            //奖惩情况
            List<RewardsPunishmentsVO> rewardsPunishmentsVO = staffFilesVO.getRewardsPunishmentsVO();
            if (CollectionUtil.isNotEmpty(rewardsPunishmentsVO)) {
                for (RewardsPunishmentsVO one : rewardsPunishmentsVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        rewardsPunishmentsService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        rewardsPunishmentsService.saveOrUpdate(one);
                    }
                }
            }
            //年度考核结果
            List<AnnualAssessmentVO> annualAssessmentVO = staffFilesVO.getAnnualAssessmentVO();
            if (CollectionUtil.isNotEmpty(annualAssessmentVO)) {
                for (AnnualAssessmentVO one : annualAssessmentVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        annualAssessmentService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        annualAssessmentService.saveOrUpdate(one);
                    }
                }
            }
            //家庭及社会关系
            List<SocialRelationsVO> socialRelationsVO = staffFilesVO.getSocialRelationsVO();
            if (CollectionUtil.isNotEmpty(socialRelationsVO)) {
                for (SocialRelationsVO one : socialRelationsVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        socialRelationsService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        socialRelationsService.saveOrUpdate(one);
                    }
                }
            }
            //从业资格证书
            List<PractitionerCertificateVO> practitionerCertificateVO = staffFilesVO.getPractitionerCertificateVO();
            if (CollectionUtil.isNotEmpty(practitionerCertificateVO)) {
                for (PractitionerCertificateVO one : practitionerCertificateVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        practitionerCertificateService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        practitionerCertificateService.saveOrUpdate(one);
                    }
                }
            }
            //专业技术资格
            List<TechnicalQualificationVO> technicalQualificationVO = staffFilesVO.getTechnicalQualificationVO();
            if (CollectionUtil.isNotEmpty(technicalQualificationVO)) {
                for (TechnicalQualificationVO one : technicalQualificationVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        technicalQualificationService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        technicalQualificationService.saveOrUpdate(one);
                    }
                }
            }
            List<TrainVO> trainVO = staffFilesVO.getTrainVO();
            if (CollectionUtil.isNotEmpty(trainVO)) {
                for (TrainVO one : trainVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        trainService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        trainService.saveOrUpdate(one);
                    }
                }
            }
            List<OverseasMembersVO> overseasMembersVO = staffFilesVO.getOverseasMembersVO();
            if (CollectionUtil.isNotEmpty(overseasMembersVO)) {
                for (OverseasMembersVO one : overseasMembersVO) {
                    if (one.getId() != null && Optional.ofNullable(one.getIsDeleted()).isPresent() && one.getIsDeleted().intValue() == 1) {
                        overseasMembersService.removeById(one.getId());
                    } else {
                        one.setStaffFilesId(staffFilesVO.getId());
                        overseasMembersService.saveOrUpdate(one);
                    }
                }
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
        return true;
    }

    @Override
    public Boolean isSame(DwhStaffManagementVO staffFilesVO, DwhStaffManagementVO oldVO) {

        StaffFiles staffFiles = new StaffFiles();
        BeanUtils.copyProperties(staffFilesVO, staffFiles);
        StaffFiles old = new StaffFiles();
        BeanUtils.copyProperties(oldVO, old);
        if (!staffFiles.equals(old)) {
            return false;
        }

        ListEqualsUtil<AppointRemoveVO> listEqualsUtil1 = new ListEqualsUtil<>();
        if (!listEqualsUtil1.listIsSame(staffFilesVO.getAppointRemoveVO(), oldVO.getAppointRemoveVO())) {
            return false;
        }

        ListEqualsUtil<RewardsPunishmentsVO> listEqualsUtil2 = new ListEqualsUtil<>();
        if (!listEqualsUtil2.listIsSame(staffFilesVO.getRewardsPunishmentsVO(), oldVO.getRewardsPunishmentsVO())) {
            return false;
        }

        ListEqualsUtil<AnnualAssessmentVO> listEqualsUtil3 = new ListEqualsUtil<>();
        if (!listEqualsUtil3.listIsSame(staffFilesVO.getAnnualAssessmentVO(), oldVO.getAnnualAssessmentVO())) {
            return false;
        }

        ListEqualsUtil<EducationDegreeVO> listEqualsUtil4 = new ListEqualsUtil<>();
        if (!listEqualsUtil4.listIsSame(staffFilesVO.getEducationDegreeVO(), oldVO.getEducationDegreeVO())) {
            return false;
        }

        ListEqualsUtil<SocialRelationsVO> listEqualsUtil5 = new ListEqualsUtil<>();
        if (!listEqualsUtil5.listIsSame(staffFilesVO.getSocialRelationsVO(), oldVO.getSocialRelationsVO())) {
            return false;
        }

        ListEqualsUtil<PractitionerCertificateVO> listEqualsUtil6 = new ListEqualsUtil<>();
        if (!listEqualsUtil6.listIsSame(staffFilesVO.getPractitionerCertificateVO(), oldVO.getPractitionerCertificateVO())) {
            return false;
        }

        ListEqualsUtil<TechnicalQualificationVO> listEqualsUtil7 = new ListEqualsUtil<>();
        if (!listEqualsUtil7.listIsSame(staffFilesVO.getTechnicalQualificationVO(), oldVO.getTechnicalQualificationVO())) {
            return false;
        }

        ListEqualsUtil<TrainVO> listEqualsUtil8 = new ListEqualsUtil<>();
        if (!listEqualsUtil8.listIsSame(staffFilesVO.getTrainVO(), oldVO.getTrainVO())) {
            return false;
        }

        ListEqualsUtil<OverseasMembersVO> listEqualsUtil9 = new ListEqualsUtil<>();
        if (!listEqualsUtil9.listIsSame(staffFilesVO.getOverseasMembersVO(), oldVO.getOverseasMembersVO())) {
            return false;
        }
        return true;
    }


    @Override
    public File createReceptFile(Long id) {
        try {
            int lenth = 0;
            String remake = "  1、侨眷是指华侨（定居在国外的中国公民）、归侨（回国定居的华侨在国内的眷属。侨眷包括：华侨、归侨的配偶，父母，子女及其配偶，兄弟姐妹，祖父母、外祖父母，孙子女、外孙子女，以及同华侨、归侨有长期无偿援助养关系的其他亲属。定居是指中国公民已取得住在国连续5年（含5年）以上合法居留资格，并在国外居住、视同定居。中国留学生（包括公派和自费）在外学习期间、因公出国人员（包括劳务人员）在外工作期间，不被视为定居。\n" +
                    "  2、工作单位及职务栏请填写××市××县（市、区）××单位××部门××职务或干××工作（外省工作的请注明××省）。在大专院校读书的子女请填写××大学××学院(系) ××专业学生。在国（境）外就读的应注明××国家××大学××学院(系) ××专业学生。在海（境）外的家庭成员请填写××国家××城市××单位××部门干××工作。\n" +
                    "  3、父母亲已去世的需填写原所在单位部门及职务，并写明“（已去世）”。\n";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            DwhStaffManagementVO bean = dwhStaffManagementWrapper.entityToVO(getById(id));
            bean = setChild(bean);
            lenth = bean.getEducationDegreeVO() == null ? 0 : bean.getEducationDegreeVO().size();
            String[][] Study = new String[lenth][3];
            for (int i = 0; i < lenth; i++) {
                Study[i][0] = bean.getEducationDegreeVO().get(i).getEducationalName();
                Study[i][1] = (bean.getEducationDegreeVO().get(i).getStartDate() == null ? "" : sdf.format(bean.getEducationDegreeVO().get(i).getStartDate())) + "--" +
                        (bean.getEducationDegreeVO().get(i).getEndDate() == null ? "" : sdf.format(bean.getEducationDegreeVO().get(i).getEndDate()));
                Study[i][2] = "";
                if (StringUtil.isNotBlank(bean.getEducationDegreeVO().get(i).getSchoolDepartmentMajor())) {
                    Study[i][2] += bean.getEducationDegreeVO().get(i).getSchoolDepartmentMajor();
                }
                if (StringUtil.isNotBlank(bean.getEducationDegreeVO().get(i).getDegreeName())) {
                    Study[i][2] += bean.getEducationDegreeVO().get(i).getDegreeName();
                }

            }
            String yearAssessment = "";
            lenth = bean.getAnnualAssessmentVO() == null ? 0 : bean.getAnnualAssessmentVO().size();
            for (int i = 0; i < lenth; i++) {
                if (StringUtil.isNotBlank(bean.getAnnualAssessmentVO().get(i).getAssessmentYear()) && StringUtil.isNotBlank(bean.getAnnualAssessmentVO().get(i).getAssessmentResult())) {
                    yearAssessment += bean.getAnnualAssessmentVO().get(i).getAssessmentYear() + "年考核" + bean.getAnnualAssessmentVO().get(i).getAssessmentResult() + ";";
                }
            }
            lenth = bean.getWorkExperienceVO() == null ? 0 : bean.getWorkExperienceVO().size();
            String[] resume = new String[lenth];
            for (int i = 0; i < lenth; i++) {
                resume[i] = (bean.getWorkExperienceVO().get(i).getStartDate() == null ? "" : sdf.format(bean.getWorkExperienceVO().get(i).getStartDate())) + "--" +
                        (bean.getWorkExperienceVO().get(i).getEndDate() == null ? "" : sdf.format(bean.getWorkExperienceVO().get(i).getEndDate())) + "   " +
                        bean.getWorkExperienceVO().get(i).getWorkUnit() + "   " + bean.getWorkExperienceVO().get(i).getJobNameId();
            }
            lenth = bean.getRewardsPunishmentsVO() == null ? 0 : bean.getRewardsPunishmentsVO().size();
            String[] rewardsPunishments = new String[lenth];
            for (int i = 0; i < lenth; i++) {
                rewardsPunishments[i] = bean.getRewardsPunishmentsVO().get(i).getRewardDate() == null ? "" : sdf.format(bean.getRewardsPunishmentsVO().get(i).getRewardDate()) + bean.getRewardsPunishmentsVO().get(i).getGrantingUnitName() + "  " +
                        bean.getRewardsPunishmentsVO().get(i).getRewardPunishmentLevel() + "  " + bean.getRewardsPunishmentsVO().get(i).getHonorAwardName();
            }
            lenth = bean.getTrainVO() == null ? 0 : bean.getTrainVO().size();
            String[][] Train = new String[lenth][2];
            for (int i = 0; i < lenth; i++) {
                Train[i][0] = (bean.getTrainVO().get(i).getStartTime() == null ? "" : sdf.format(bean.getTrainVO().get(i).getStartTime())) + "--" +
                        (bean.getTrainVO().get(i).getEndTime() == null ? "" : sdf.format(bean.getTrainVO().get(i).getEndTime()));
                Train[i][1] = bean.getTrainVO().get(i).getClasses();
            }
            lenth = bean.getSocialRelationsVO() == null ? 0 : bean.getSocialRelationsVO().size();
            String[][] socialRelations = new String[lenth][5];
            for (int i = 0; i < lenth; i++) {
                socialRelations[i][0] = bean.getSocialRelationsVO().get(i).getAppellation();
                socialRelations[i][1] = bean.getSocialRelationsVO().get(i).getFullName();
                socialRelations[i][2] = bean.getSocialRelationsVO().get(i).getBirthday() == null ? "" : sdf.format(bean.getSocialRelationsVO().get(i).getBirthday());
                socialRelations[i][3] = bean.getSocialRelationsVO().get(i).getPoliticCountenanceName();
                socialRelations[i][4] = bean.getSocialRelationsVO().get(i).getWorkUnit() + bean.getSocialRelationsVO().get(i).getJobNameId();
            }

            lenth = bean.getOverseasMembersVO() == null ? 0 : bean.getOverseasMembersVO().size();
            String[][] overseasMembers = new String[lenth][4];
            for (int i = 0; i < lenth; i++) {
                overseasMembers[i][0] = bean.getOverseasMembersVO().get(i).getOverseasName();
                overseasMembers[i][1] = bean.getOverseasMembersVO().get(i).getOverseasSexName();
                overseasMembers[i][2] = bean.getOverseasMembersVO().get(i).getHostCountry() + bean.getOverseasMembersVO().get(i).getOccupation();
                overseasMembers[i][3] = bean.getOverseasMembersVO().get(i).getRelationship();
            }


            Document document = new Document(PageSize.A4, 90, 83, 30, 40);
            FileOutputStream fs;
            BaseFont bfHeiTi;
            BaseFont bfST;
            BaseFont test;
            BaseFont bfbt;

            File pdffile = File.createTempFile(id.toString(), ".pdf");
            if (pdffile.exists()) {
                pdffile.delete();
            }
            fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
            PdfWriter.getInstance(document, fs);
            // 打开文档
            document.open();
            bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 创建了一页
            Font font_Zhengwen = new Font(bfST, 12.0f, Font.NORMAL, BaseColor.BLACK);
            // 添加标题
            Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
            Font font_biaotou1 = new Font(test, 12.0f, Font.NORMAL, BaseColor.BLACK);
            Font font_biaotou2 = new Font(bfbt, 12.0f, Font.NORMAL, BaseColor.BLACK);
            // 创建一个段落
            String title = "个人基本情况表";
            Paragraph biaoti = new Paragraph(title, font_Biaoti);
            biaoti.setAlignment(1);
            biaoti.setSpacingAfter(20f);
            document.add(biaoti);
            float[] widths = {60f, 60f, 60f, 60f, 30f, 30f, 30f, 30f};// 设置表格的列宽
            PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格
            table.setSpacingBefore(10f);// 设置表格上面空白宽度
            table.setSpacingAfter(0f);// 设置表格下面空白宽度
            table.setTotalWidth(420);// 设置表格的宽度
            PdfPCell cell = new PdfPCell();
            PdfPCell cell2 = new PdfPCell();
            cell.setMinimumHeight(25f);
            cell2.setMinimumHeight(25f);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPaddingTop(5);
            cell.setPaddingBottom(5);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setPaddingTop(5);
            cell2.setPaddingBottom(5);
            table.setLockedWidth(true);

            //正式开始
            cell.setPhrase(new Paragraph("姓名", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getStaffName(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("出生年月", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getBirthday() == null ? "" : sdf.format(bean.getBirthday()), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("性别", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getGenderName(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("民族", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getNationName(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("籍贯", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setRowspan(1);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getNativePlace(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("入党时间", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getJoinPartyTime() == null ? "" : sdf.format(bean.getJoinPartyTime()), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("健康状况", font_biaotou2));
            cell.setColspan(2);
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getHealthConditionName(), font_Zhengwen));
            cell2.setColspan(2);
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("出生地", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getBirthPlace(), font_Zhengwen));
            cell2.setColspan(1);
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("参加工作时间", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getWorkTime() == null ? "" : bean.getWorkTime(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("熟悉专业\n有何专长", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            cell.setRowspan(2);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getExpertise(), font_Zhengwen));
            cell2.setColspan(2);
            cell2.setRowspan(2);
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("学历", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getEducationalName(), font_Zhengwen));
            cell2.setColspan(1);
            cell2.setRowspan(1);
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("学位或专业\n技术职称", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            if (StringUtil.isBlank(bean.getDegreeName())) {
                bean.setDegreeName("");
            }
            if (StringUtil.isBlank(bean.getTechnicalPosition())) {
                bean.setTechnicalPosition("");
            }
            cell2.setPhrase(new Paragraph(bean.getDegreeName() + bean.getTechnicalPosition(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("现任职务", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getJobNameName(), font_Zhengwen));
            cell2.setColspan(7);
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("岗位职责", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getResponsibilities(), font_Zhengwen));
            table.addCell(cell2);

            document.add(table);//第一组结束

            float[] widths2 = {25f, 35f, 90f, 210f};// 设置表格的列宽
            PdfPTable table2 = new PdfPTable(widths2);// 建立一个pdf表格
            table2.setSpacingBefore(0f);// 设置表格上面空白宽度
            table2.setSpacingAfter(0f);// 设置表格下面空白宽度
            table2.setTotalWidth(420);// 设置表格的宽度
            table2.setLockedWidth(true);

            cell.setPhrase(new Paragraph("历次\n学历\n学习\n情况", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(Study.length < 4 ? 5 : Study.length + 1);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("学历", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("起止时间", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("院校、系、专业及学位", font_biaotou2));
            cell.setColspan(1);
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            lenth = Study.length < 4 ? 4 : Study.length;
            for (int i = 0; i < lenth; i++) {
                for (int j = 0; j < 3; j++) {
                    if (i < Study.length) {
                        cell2.setPhrase(new Paragraph(Study[i][j], font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    cell2.setColspan(1);
                    cell2.setRowspan(1);
                    table2.addCell(cell2);
                }
            }

            cell.setPhrase(new Paragraph("年度\n考核", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table2.addCell(cell);
            cell2.setPhrase(new Paragraph(yearAssessment, font_Zhengwen));
            cell2.setColspan(3);
            cell2.setRowspan(1);
            table2.addCell(cell2);

            cell.setPhrase(new Paragraph("简 \n\n\n\n\n\n历", font_biaotou1));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setMinimumHeight(250f);
            table2.addCell(cell);
            String jl = StringUtils.join(resume, "\n");
            if (StringUtil.isBlank(jl)) {
                jl = "";
            }
            cell2.setPhrase(new Paragraph(jl, font_Zhengwen));
            //cell2.setHorizontalAlignment(Element.ALIGN_TOP);
            cell2.setColspan(3);
            table2.addCell(cell2);

            document.add(table2);

            document.newPage();
            float[] widths21 = {25f, 35f, 120f, 180f};// 设置表格的列宽
            PdfPTable table21 = new PdfPTable(widths21);// 建立一个pdf表格
            table21.setSpacingBefore(0f);// 设置表格上面空白宽度
            table21.setSpacingAfter(0f);// 设置表格下面空白宽度
            table21.setTotalWidth(420);// 设置表格的宽度
            table21.setLockedWidth(true);

            cell.setPhrase(new Paragraph("奖惩\n情况", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(2);
            cell.setMinimumHeight(40f);
            table21.addCell(cell);
            String j2 = StringUtils.join(rewardsPunishments, "\n");
            cell2.setPhrase(new Paragraph(j2, font_Zhengwen));
            cell2.setColspan(3);
            cell2.setRowspan(2);
            table21.addCell(cell2);

            cell.setPhrase(new Paragraph("近五\n年三\n个月\n以上\n培训、\n学习\n情况", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(Train.length < 3 ? 4 : Train.length + 1);
            cell.setMinimumHeight(30f);
            table21.addCell(cell);
            cell.setPhrase(new Paragraph("起止时间", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            cell.setRowspan(1);
            table21.addCell(cell);
            cell.setPhrase(new Paragraph("班      次", font_biaotou2));
            cell.setColspan(1);
            cell.setRowspan(1);
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table21.addCell(cell);
            lenth = Train.length < 3 ? 3 : Study.length;
            for (int i = 0; i < lenth; i++) {
                for (int j = 0; j < 2; j++) {
                    if (i < Train.length) {
                        cell2.setPhrase(new Paragraph(Train[i][j], font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    switch (j) {
                        case 0:
                            cell2.setColspan(2);
                            break;
                        case 1:
                            cell2.setColspan(1);
                            break;
                    }
                    cell2.setRowspan(1);
                    table21.addCell(cell2);
                }
            }
            document.add(table21);//第二组结束

            float[] widths3 = {25f, 55f, 50f, 50f, 50f, 130f};
            PdfPTable table3 = new PdfPTable(widths3);
            table3.setSpacingBefore(0f);
            table3.setSpacingAfter(0f);
            table3.setTotalWidth(420);
            table3.setLockedWidth(true);

            cell.setPhrase(new Paragraph("家庭\n主要\n成员\n及\n重要\n社会\n关系", font_biaotou1));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(socialRelations.length < 5 ? 6 : socialRelations.length + 1);
            table3.addCell(cell);
            cell.setPhrase(new Paragraph("称谓", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table3.addCell(cell);
            cell.setPhrase(new Paragraph("姓名", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table3.addCell(cell);
            cell.setPhrase(new Paragraph("出生年月", font_biaotou2));
            cell.setColspan(1);
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table3.addCell(cell);
            cell.setPhrase(new Paragraph("政治面貌", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table3.addCell(cell);
            cell.setPhrase(new Paragraph("工作单位及职务", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table3.addCell(cell);
            lenth = socialRelations.length < 5 ? 5 : Study.length;
            for (int i = 0; i < lenth; i++) {
                for (int j = 0; j < 5; j++) {
                    if (i < socialRelations.length) {
                        cell2.setPhrase(new Paragraph(socialRelations[i][j], font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    cell2.setRowspan(1);
                    table3.addCell(cell2);
                }
            }
            document.add(table3);

            float[] widths4 = {25f, 55f, 50f, 150f, 80f};
            PdfPTable table4 = new PdfPTable(widths4);
            table4.setSpacingBefore(0f);
            table4.setSpacingAfter(0f);
            table4.setTotalWidth(420);
            table4.setLockedWidth(true);

            cell.setPhrase(new Paragraph("侨眷\n情况", font_biaotou1));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(overseasMembers.length < 1 ? 2 : overseasMembers.length + 1);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("华侨、归侨\n姓名", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("性别", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("所在国家、城市、职业", font_biaotou2));
            cell.setColspan(1);
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("与本人的\n眷属关系", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table4.addCell(cell);
            lenth = overseasMembers.length < 1 ? 1 : Study.length;
            for (int i = 0; i < lenth; i++) {
                for (int j = 0; j < 4; j++) {
                    if (i < overseasMembers.length) {
                        cell2.setPhrase(new Paragraph(overseasMembers[i][j], font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    cell2.setColspan(1);
                    table4.addCell(cell2);
                }
            }

            cell.setPhrase(new Paragraph("本人身份证号", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            table4.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getDocumentNumber(), font_Zhengwen));
            cell2.setColspan(3);
            table4.addCell(cell2);

            cell.setPhrase(new Paragraph("家庭地址", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            table4.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getFamilyAddress(), font_Zhengwen));
            cell2.setColspan(3);
            table4.addCell(cell2);

            cell.setPhrase(new Paragraph("填\n报\n说\n明", font_biaotou2));
            //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table4.addCell(cell);
            cell2.setPhrase(new Paragraph(remake, font_Zhengwen));
            cell2.setColspan(4);
            table4.addCell(cell2);
            document.add(table4);
            document.close();

            return pdffile;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return null;
    }


    private void initMap() {
        //注：以下key值与实际配置的参照无关联，仅为了方便理解使用了相同名称
        //职务名称
//		codeMap.put("jobNameRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.JOB_NAME).keySet()));
        //证件类型
        codeMap.put("documentTypeRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.DOCUMENT_TYPE).keySet()));
        //性别
        codeMap.put("genderRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.GENDER).keySet()));
        //民族
        codeMap.put("nationRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.NATION).keySet()));
        //政治面貌
        codeMap.put("politicCountenanceRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.POLITIC_COUNTENANCE).keySet()));
        //国籍
        codeMap.put("nationalityRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.NATIONALITY).keySet()));
        //婚姻状态
        codeMap.put("maritalStatusRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.MARITAL_STATUS).keySet()));
        //最高学历
        codeMap.put("educationalRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.EDUCATION).keySet()));
        //最高学位
        codeMap.put("degreeRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.DEGREE).keySet()));
        //管理类别
        codeMap.put("managementCategoryRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.MANAGEMENT_CATEGORY).keySet()));
        //编制类型
        codeMap.put("compilationTypeRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.COMPILATION_TYPE).keySet()));
        //人员类型
        codeMap.put("staffTypeRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.STAFF_TYPE).keySet()));
        //人员类别
        codeMap.put("staffCategoryRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.STAFF_CATEGORY).keySet()));
        //职务类别
        codeMap.put("jobCategoryRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.JOB_CATEGORY).keySet()));
        //职级
        codeMap.put("rankRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.RANK).keySet()));
        //职等
        codeMap.put("gradePositionsRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.GRADE_POSITIONS).keySet()));
        //异动事件
        codeMap.put("changeEventsRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.CHANGE_EVENTS).keySet()));
        //异动类型
        codeMap.put("changeTypeRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.CHANGE_TYPE).keySet()));
        // 健康状况
        codeMap.put("healthConditionRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.HEALTH_CONDITION).keySet()));

        try {
            List<PageData> allOrgs = orgzationDao.list(null);
            //单位
            if (CollectionUtil.isNotEmpty(allOrgs)) {
                HashMap<String, String> orgMap = new HashMap<>();
                for (PageData pageData : allOrgs) {
                    orgMap.put((String) pageData.get("name"), (String) pageData.get("id"));
                }

                nameMap.put("unitRef", orgMap);
            }

            //  部门
            allOrgs.parallelStream().forEach(pd -> deptUnitMap.put((String) pd.get("id"), new HashMap<>()));
            allOrgs.parallelStream().forEach(pd -> deptUnitCodeMap.put((String) pd.get("id"), new HashMap<>()));
            deptService.list().parallelStream().forEach(x -> {
                //针对服务器可能存在部门未删除，但对应单位已删除的脏数据问题，每次进行对应key校验
                if (deptUnitMap.containsKey(x.getDeptAffiliation())) {
                    deptUnitMap.get(x.getDeptAffiliation()).put(x.getDeptName(), x.getId());
                }
                if (deptUnitCodeMap.containsKey(x.getDeptAffiliation())) {
                    deptUnitCodeMap.get(x.getDeptAffiliation()).put(x.getDeptName(), x.getDeptCode());
                }
            });

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

        //子表使用参照
        //教育类型
        codeMap.put("educationTypeRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.EDUCATION_TYPE).keySet()));
        //专业技术职务级别
        codeMap.put("technicalTitleLevelRef", new ArrayList<>(baseInfoService.getChildMap(ValueSetConstant.TECHNICAL_TITLE_LEVEL).keySet()));
    }

    public List<DwhStaffManagementVO> setVO(List<DwhStaffManagement> staffFilesList) {
        if (CollectionUtil.isEmpty(staffFilesList)) {
            return new ArrayList<>();
        }
        allCodeMap = baseInfoService.getChildMap(ValueSetConstant.ROOT);
        deptService.list().parallelStream().forEach(dept -> deptMap.put(dept.getId(), dept.getDeptName()));
        List<PageData> pageDataList = (List<PageData>) orgzationService.listAll().getPageData().get("list");
        pageDataList.parallelStream().forEach(pd -> orgMap.put((String) pd.get("id"), pd.get("name") + StringPool.DASH + pd.get("orgCode")));
        List<DwhStaffManagementVO> staffFilesVOS = new ArrayList<>();
        for (DwhStaffManagement staffFiles : staffFilesList) {
            staffFilesVOS.add(entityToVo(staffFiles));
        }
        return staffFilesVOS;
    }

    public List<DwhStaffManagementVO> getBaseInfoByCompanyId(List<DwhStaffManagement> staffFilesList) {
        if (CollectionUtil.isEmpty(staffFilesList)) {
            return new ArrayList<>();
        }
        allCodeMap = baseInfoService.getChildMap(ValueSetConstant.ROOT);
        deptService.list().parallelStream().forEach(dept -> deptMap.put(dept.getId(), dept.getDeptName()));
        List<PageData> pageDataList = (List<PageData>) orgzationService.listAll().getPageData().get("list");
        pageDataList.parallelStream().forEach(pd -> orgMap.put((String) pd.get("id"), pd.get("name") + StringPool.DASH + pd.get("orgCode")));
        List<DwhStaffManagementVO> staffFilesVOS = new ArrayList<>();
        for (DwhStaffManagement staffFiles : staffFilesList) {
            DwhStaffManagementVO staffFilesVO = entityToVo(staffFiles);
            //学历学位
            List<EducationDegree> educationDegrees = educationDegreeService.ListByPid(staffFiles.getId());
            if (CollectionUtil.isNotEmpty(educationDegrees)) {

                for (EducationDegree educationDegree : educationDegrees) {
                    if ("037001".equals(educationDegree.getEducationTypeId())) {
                        staffFilesVO.setFulltimeSchoolMajor(educationDegree.getSchoolDepartmentMajor());
                    } else if ("037002".equals(educationDegree.getEducationTypeId())) {
                        staffFilesVO.setOnjobSchoolMajor(educationDegree.getSchoolDepartmentMajor());
                    }
                }
            }
            staffFilesVO.setStaffNameId("");
            staffFilesVO.setPresentPostId(staffFiles.getJobNameId());
            staffFilesVOS.add(staffFilesVO);
        }
        return staffFilesVOS;
    }


    @Override
    public void encryptBase64Data(DwhStaffManagementVO staffFilesVO) {
        if (StringUtil.isNotBlank(staffFilesVO.getStaffCode())) {
            staffFilesVO.setStaffCode(EncryptUtil.encryptBase64(staffFilesVO.getStaffCode(), BASE64_KEY));
        }
        if (StringUtil.isNotBlank(staffFilesVO.getDocumentNumber())) {
            staffFilesVO.setDocumentNumber(EncryptUtil.encryptBase64(staffFilesVO.getDocumentNumber(), BASE64_KEY));
        }
    }

    private DwhStaffManagementVO entityToVo(DwhStaffManagement staffFiles) {
        DwhStaffManagementVO staffFilesVO = new DwhStaffManagementVO();
        BeanUtils.copyProperties(staffFiles, staffFilesVO);
        if (StringUtil.isNotBlank(staffFiles.getStaffCode())) {
            staffFilesVO.setStaffCode(EncryptUtil.decryptBase64(staffFiles.getStaffCode(), BASE64_KEY));
        }
        if (StringUtil.isNotBlank(staffFiles.getDocumentNumber())) {
            staffFilesVO.setDocumentNumber(EncryptUtil.decryptBase64(staffFiles.getDocumentNumber(), BASE64_KEY));
        }
        if (StringUtil.isNotBlank(staffFilesVO.getDocumentTypeId()) && allCodeMap.containsKey(staffFilesVO.getDocumentTypeId())) {
            staffFilesVO.setDocumentTypeName(allCodeMap.get(staffFilesVO.getDocumentTypeId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getGenderId()) && allCodeMap.containsKey(staffFilesVO.getGenderId())) {
            staffFilesVO.setGenderName(allCodeMap.get(staffFilesVO.getGenderId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getNationId()) && allCodeMap.containsKey(staffFilesVO.getNationId())) {
            staffFilesVO.setNationName(allCodeMap.get(staffFilesVO.getNationId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getPoliticCountenanceId()) && allCodeMap.containsKey(staffFilesVO.getPoliticCountenanceId())) {
            staffFilesVO.setPoliticCountenanceName(allCodeMap.get(staffFilesVO.getPoliticCountenanceId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getNationalityId()) && allCodeMap.containsKey(staffFilesVO.getNationalityId())) {
            staffFilesVO.setNationalityName(allCodeMap.get(staffFilesVO.getNationalityId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getMaritalStatusId()) && allCodeMap.containsKey(staffFilesVO.getMaritalStatusId())) {
            staffFilesVO.setMaritalStatusName(allCodeMap.get(staffFilesVO.getMaritalStatusId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getEducationalId()) && allCodeMap.containsKey(staffFilesVO.getEducationalId())) {
            staffFilesVO.setEducationalName(allCodeMap.get(staffFilesVO.getEducationalId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getDegreeId()) && allCodeMap.containsKey(staffFilesVO.getDegreeId())) {
            staffFilesVO.setDegreeName(allCodeMap.get(staffFilesVO.getDegreeId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getManagementCategoryId()) && allCodeMap.containsKey(staffFilesVO.getManagementCategoryId())) {
            staffFilesVO.setManagementCategoryName(allCodeMap.get(staffFilesVO.getManagementCategoryId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getCompilationTypeId()) && allCodeMap.containsKey(staffFilesVO.getCompilationTypeId())) {
            staffFilesVO.setCompilationTypeName(allCodeMap.get(staffFilesVO.getCompilationTypeId()));
        }

//		if (StringUtil.isNotBlank(staffFilesVO.getStaffTypeId()) && allCodeMap.containsKey(staffFilesVO.getStaffTypeId())) {
//			staffFilesVO.setStaffTypeName(allCodeMap.get(staffFilesVO.getStaffTypeId()));
//		}
//
//		if (StringUtil.isNotBlank(staffFilesVO.getStaffCategoryId()) && allCodeMap.containsKey(staffFilesVO.getStaffCategoryId())) {
//			staffFilesVO.setStaffCategoryName(allCodeMap.get(staffFilesVO.getStaffCategoryId()));
//		}

        if (StringUtil.isNotBlank(staffFilesVO.getJobCategoryId()) && allCodeMap.containsKey(staffFilesVO.getJobCategoryId())) {
            staffFilesVO.setJobCategoryName(allCodeMap.get(staffFilesVO.getJobCategoryId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getRankId()) && allCodeMap.containsKey(staffFilesVO.getRankId())) {
            staffFilesVO.setRankName(allCodeMap.get(staffFilesVO.getRankId()));
        }

//		if (StringUtil.isNotBlank(staffFilesVO.getGradePositionsId()) && allCodeMap.containsKey(staffFilesVO.getGradePositionsId())) {
//			staffFilesVO.setGradePositionsName(allCodeMap.get(staffFilesVO.getGradePositionsId()));
//		}

        if (StringUtil.isNotBlank(staffFilesVO.getChangeEventsId()) && allCodeMap.containsKey(staffFilesVO.getChangeEventsId())) {
            staffFilesVO.setChangeEventsName(allCodeMap.get(staffFilesVO.getChangeEventsId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getChangeTypeId()) && allCodeMap.containsKey(staffFilesVO.getChangeTypeId())) {
            staffFilesVO.setChangeTypeName(allCodeMap.get(staffFilesVO.getChangeTypeId()));
        }

        if (StringUtil.isNotBlank(staffFilesVO.getHealthConditionId()) && allCodeMap.containsKey(staffFilesVO.getHealthConditionId())) {
            staffFilesVO.setHealthConditionName(allCodeMap.get(staffFilesVO.getHealthConditionId()));
        }

        if (StringUtils.isNotBlank(staffFilesVO.getDepartmentNameId())) {
            if (deptMap.containsKey(Long.valueOf(staffFilesVO.getDepartmentNameId()))) {
                staffFilesVO.setDepartmentName(deptMap.get(Long.valueOf(staffFilesVO.getDepartmentNameId())));
            }
        }
        if (StringUtil.isNotBlank(staffFilesVO.getCompanyNameId())) {
            if (orgMap.containsKey(staffFilesVO.getCompanyNameId())) {
                String[] strs = orgMap.get(staffFilesVO.getCompanyNameId()).split(StringPool.DASH);

                staffFilesVO.setCompanyName(strs[0]);
                staffFilesVO.setCompanyCode(strs[1]);
            }
        }
        if (StringUtil.isBlank(staffFilesVO.getJobNameId())) {
            staffFilesVO.setJobNameId("");
        }
        staffFilesVO.setJobNameName(staffFilesVO.getJobNameId());

        if (staffFilesVO.getBirthday() != null) {
            staffFilesVO.setBirthdayStr(DateUtil.format(staffFilesVO.getBirthday(), DateUtil.PATTERN_DATE));
        }

        if (staffFilesVO.getJoinPartyTime() != null) {
            staffFilesVO.setJoinPartyTimeStr(DateUtil.format(staffFilesVO.getJoinPartyTime(), DateUtil.PATTERN_MONTH));
        }

        if (staffFilesVO.getChangeTime() != null) {
            staffFilesVO.setChangeTimeStr(DateUtil.format(staffFilesVO.getChangeTime(), DateUtil.PATTERN_MONTH));
        }

        if (staffFilesVO.getChangeDateTime() != null) {
            staffFilesVO.setChangeDateTimeStr(DateUtil.format(staffFilesVO.getChangeDateTime(), DateUtil.PATTERN_MONTH));
        }

        if (staffFilesVO.getApprovedTime() != null) {
            staffFilesVO.setApprovedTimeStr(DateUtil.format(staffFilesVO.getApprovedTime(), DateUtil.PATTERN_MONTH));
        }
        //单独处理数字宁波同步部门信息
        if (StringUtil.isNotBlank(staffFiles.getDataSource()) && staffFiles.getDataSource().equals("3")) {
            staffFilesVO.setDepartmentName(StringUtils.isNotBlank(staffFiles.getDef1()) ? staffFiles.getDef1() : null);
        }
        return staffFilesVO;
    }

    @Override
    public R submit(DwhStaffManagementVO staffFilesVO) {
        String checkResult = "";
        encryptBase64Data(staffFilesVO);
        if (!(Optional.ofNullable(staffFilesVO.getStatus()).isPresent() && staffFilesVO.getStatus() == FormStatusConstant.STASH)) {
            checkResult = checkIsExisted(staffFilesVO.getId(), staffFilesVO.getStaffCode(), staffFilesVO.getCompanyNameId());
        }

        if (StringUtil.isBlank(checkResult)) {
            if (!checkDocumentNumber(staffFilesVO.getId(), staffFilesVO.getCompanyNameId(), staffFilesVO.getDocumentNumber())) {
                return new R(CustomCode.builder().message("证件号已存在").code(1999).success(false).build());
            }

            boolean sameFlag = true;
            DwhStaffManagementVO oldVO = new DwhStaffManagementVO();
            if (staffFilesVO.getId() != null) {
                oldVO = dwhStaffManagementWrapper.entityToVO(getById(staffFilesVO.getId()));
                setChild(oldVO);
                sameFlag = isSame(staffFilesVO, oldVO);
            }
            DwhStaffManagement staffFiles = dwhStaffManagementWrapper.voToEntity(staffFilesVO);
            boolean result = saveOrUpdate(staffFiles);

            if (result) {
                staffFilesVO.setId(staffFiles.getId());
                saveChild(staffFilesVO);

                if(staffFilesVO.getStatus() == 3){
                    // 反审核
                    goBackToStash(String.valueOf(staffFiles.getId()));
                    workflowTwoService.goBackToStash(String.valueOf(staffFiles.getId()), FormTypeConstant.HR_STAFFFILES_FORM);
                }

                if (!sameFlag) {
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        formHistoryRecordService.submit(FormHistoryRecord.builder().formType(String.valueOf(FormTypeConstant.DWH_STAFF_FORM))
                                .record(mapper.writeValueAsString(oldVO)).recordId(staffFiles.getId()).build());
                    } catch (Exception e) {
                        log.error("党委会档案--> 历史数据版本保存失败");
                    }
                }
            }
            HashMap<String, Object> processVariable = new HashMap<>();
            formWorkflowService.startProcessAndSimulate(String.valueOf(staffFiles.getId()), staffFiles.getFormType(), processVariable);
            return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);

        } else {
            return new R(CustomCode.builder().message(checkResult).code(1999).success(false).build());
        }
    }

    /**
     * 得到库中存在的数据
     *
     * @param staffInfos
     * @return
     */
    private List<DwhStaffManagementVO> getYthData(List<DwhStaffManagementVO> staffInfos) {
        List<String> dataSoureIds = staffInfos.stream().map(DwhStaffManagementVO::getDataSourceId).collect(Collectors.toList());

        List<DwhStaffManagement> oldStaffils = list(Wrappers.<DwhStaffManagement>lambdaQuery().eq(DwhStaffManagement::getDataSource, YthConstant.DATA_NINGBO).in(DwhStaffManagement::getDataSourceId, dataSoureIds));
        List<DwhStaffManagementVO> staffFilesVOS = new ArrayList<>();

        for (DwhStaffManagement staffFiles : oldStaffils) {
            DwhStaffManagementVO staffFilesVO = dwhStaffManagementWrapper.entityToVO(staffFiles);
            staffFilesVO.setAppointRemoveVO(appointRemoveWrapper.entityToVO(appointRemoveService
                    .list(new LambdaQueryWrapper<AppointRemove>().eq(AppointRemove::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setWorkExperienceVO(workExperienceWrapper.entityToVO(workExperienceService
                    .list(new LambdaQueryWrapper<WorkExperience>().eq(WorkExperience::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setRewardsPunishmentsVO(rewardsPunishmentsWrapper.entityToVO(rewardsPunishmentsService
                    .list(new LambdaQueryWrapper<RewardsPunishments>().eq(RewardsPunishments::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setAnnualAssessmentVO(annualAssessmentWrapper.entityToVO(annualAssessmentService
                    .list(new LambdaQueryWrapper<AnnualAssessment>().eq(AnnualAssessment::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setEducationDegreeVO(educationDegreeWrapper.entityToVO((educationDegreeService
                    .list(new LambdaQueryWrapper<EducationDegree>().eq(EducationDegree::getStaffFilesId, staffFilesVO.getId())))));
            staffFilesVO.setSocialRelationsVO(socialRelationsWrapper.entityToVO(socialRelationsService
                    .list(new LambdaQueryWrapper<SocialRelations>().eq(SocialRelations::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setPractitionerCertificateVO(practitionerCertificateWrapper.entityToVO(practitionerCertificateService
                    .list(new LambdaQueryWrapper<PractitionerCertificate>().eq(PractitionerCertificate::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setTechnicalQualificationVO(technicalQualificationWrapper.entityToVO(technicalQualificationService
                    .list(new LambdaQueryWrapper<TechnicalQualification>().eq(TechnicalQualification::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setTrainVO(trainWrapper.entityToVO(trainService
                    .list(new LambdaQueryWrapper<Train>().eq(Train::getStaffFilesId, staffFilesVO.getId()))));
            staffFilesVO.setOverseasMembersVO(overseasMembersWrapper.entityToVO(overseasMembersService
                    .list(new LambdaQueryWrapper<OverseasMembers>().eq(OverseasMembers::getStaffFilesId, staffFilesVO.getId()))));

            staffFilesVOS.add(staffFilesVO);
        }
        return staffFilesVOS;
    }

    /**
     * 保存其它信息
     *
     * @param syncData
     */
    private void createOtherInfos(DwhStaffManagementVO syncData) {
        //工作经验
        if (CollectionUtil.isNotEmpty(syncData.getWorkExperienceVO())) {
            syncData.getWorkExperienceVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            workExperienceService.saveOrUpdateBatch(workExperienceWrapper.voToEntity(syncData.getWorkExperienceVO()));
        }

        //教育背景
        if (CollectionUtil.isNotEmpty(syncData.getEducationDegreeVO())) {
            syncData.getEducationDegreeVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            educationDegreeService.saveOrUpdateBatch(educationDegreeWrapper.voToEntity(syncData.getEducationDegreeVO()));
        }

        //任免信息
        if (CollectionUtil.isNotEmpty(syncData.getAppointRemoveVO())) {
            syncData.getAppointRemoveVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            appointRemoveService.saveOrUpdateBatch(appointRemoveWrapper.voToEntity(syncData.getAppointRemoveVO()));
        }


        //奖赏信息
        if (CollectionUtil.isNotEmpty(syncData.getRewardsPunishmentsVO())) {
            syncData.getRewardsPunishmentsVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            rewardsPunishmentsService.saveOrUpdateBatch(rewardsPunishmentsWrapper.voToEntity(syncData.getRewardsPunishmentsVO()));
        }


        //年度考核结果
        if (CollectionUtil.isNotEmpty(syncData.getAnnualAssessmentVO())) {
            syncData.getAnnualAssessmentVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            annualAssessmentService.saveOrUpdateBatch(annualAssessmentWrapper.voToEntity(syncData.getAnnualAssessmentVO()));
        }

        //家庭社会关系
        if (CollectionUtil.isNotEmpty(syncData.getSocialRelationsVO())) {
            syncData.getSocialRelationsVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            socialRelationsService.saveOrUpdateBatch(socialRelationsWrapper.voToEntity(syncData.getSocialRelationsVO()));
        }

        //从业资格证书
        if (CollectionUtil.isNotEmpty(syncData.getPractitionerCertificateVO())) {
            syncData.getPractitionerCertificateVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            practitionerCertificateService.saveOrUpdateBatch(practitionerCertificateWrapper.voToEntity(syncData.getPractitionerCertificateVO()));
        }

        //专业技术资格
        if (CollectionUtil.isNotEmpty(syncData.getTechnicalQualificationVO())) {
            syncData.getTechnicalQualificationVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            technicalQualificationService.saveOrUpdateBatch(technicalQualificationWrapper.voToEntity(syncData.getTechnicalQualificationVO()));
        }


        //近五年三个月以上培训情况
        if (CollectionUtil.isNotEmpty(syncData.getTrainVO())) {
            syncData.getTrainVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            trainService.saveOrUpdateBatch(trainWrapper.voToEntity(syncData.getTrainVO()));
        }

        //侨眷情况
        if (CollectionUtil.isNotEmpty(syncData.getOverseasMembersVO())) {
            syncData.getOverseasMembersVO().forEach(e -> e.setStaffFilesId(syncData.getId()));
            overseasMembersService.saveOrUpdateBatch(overseasMembersWrapper.voToEntity(syncData.getOverseasMembersVO()));
        }
    }

    @Override
    public ProStaffInfoVO staffInfo(String proId) {
        List<DwhStaffManagement> staffFiles = new ArrayList<>();
        //获取组织下的人员
        PropertyBasics basics = propertyBasicsMapper.selectById(proId);
        int staffNumber = 0;
        int directorNumber = 0;
        int supervisorNumber = 0;
        int partyNumber = 0;
        List<MainStaffInfoVO> mainStaffInfoVOS = new ArrayList<>();
        if (Optional.ofNullable(basics).isPresent()) {
            if (Optional.ofNullable(basics.getOrgId()).isPresent()) {
                List<Director> directors = directorMapper.selectList(Wrappers.<Director>lambdaQuery().eq(Director::getCreateCompanyId, basics.getOrgId()));
                if (CollectionUtil.isNotEmpty(directors)) {
                    directorNumber = directors.size();
                }
                List<Supervisor> supervisors = supervisorMapper.selectList(Wrappers.<Supervisor>lambdaQuery().eq(Supervisor::getCreateCompanyId, basics.getOrgId()));
                if (CollectionUtil.isNotEmpty(supervisors)) {
                    supervisorNumber = supervisors.size();
                }
                staffFiles = list(Wrappers.<DwhStaffManagement>lambdaQuery().eq(DwhStaffManagement::getCompanyNameId, basics.getOrgId()));
            }
        }
        if (CollectionUtil.isNotEmpty(staffFiles)) {
            staffNumber = staffFiles.size();
            //党员数量
            partyNumber = (int) staffFiles.stream().filter(m -> Optional.ofNullable(m.getPoliticCountenanceId()).isPresent() && "022001".equals(m.getPoliticCountenanceId())).count();

            //主要人员
            List<DwhStaffManagement> sortStaffes = staffFiles.stream().filter(m -> Optional.ofNullable(m.getOrderNumber()).isPresent() && Optional.ofNullable(m.getDepartmentCode()).isPresent())
                    .sorted(Comparator.comparing(DwhStaffManagement::getOrderNumber).thenComparing(DwhStaffManagement::getDepartmentCode)).collect(Collectors.toList());
            if (sortStaffes.size() > 10) {
                sortStaffes = sortStaffes.subList(0, 10);
            }
            //code
            List<Dict> dictList = dictService.list(Wrappers.<Dict>lambdaQuery().likeRight(Dict::getCode, managementCategoryCode));
            sortStaffes.forEach(staff -> {
                MainStaffInfoVO mainStaffInfoVO = new MainStaffInfoVO();
                mainStaffInfoVO.setStaffId(staff.getId());
                mainStaffInfoVO.setStaffName(staff.getStaffName());
                // 职务
                mainStaffInfoVO.setPositionName(staff.getJobNameId());
                mainStaffInfoVO.setCompanyInitiationTime(staff.getCompanyInitiationTime());
                Optional.ofNullable(staff.getManagementCategoryId()).ifPresent(code -> {
                    dictList.stream().filter(m -> code.equals(m.getCode())).findFirst().ifPresent(dict -> {
                        mainStaffInfoVO.setManagementCategoryName(dict.getName());
                    });
                });
                mainStaffInfoVOS.add(mainStaffInfoVO);
            });

        }
        return ProStaffInfoVO.builder().staffNumber(staffNumber).directorNumber(directorNumber).supervisorNumber(supervisorNumber).partyNumber(partyNumber).mainStaffInfoVOS(mainStaffInfoVOS).build();
    }

    /**
     * @param value
     * @return
     */
    private String transDeptId(String value, String orgId) {
        if (StringUtil.isNotBlank(value)) {
            List<Dept> deptList = deptService.list(Wrappers.<Dept>lambdaQuery().eq(Dept::getDeptAffiliation, orgId)
                    .like(Dept::getDeptName, value));
            if (CollectionUtil.isNotEmpty(deptList)) {
                return deptList.get(0).getId().toString();
            }
        }
        return null;
    }

}